简体   繁体   English

Rspec - 测试rails视图呈现特定部分

[英]Rspec - Test that rails view renders a specific partial

I have a rails 3.2.13 app running rspec-rails 2.14.0 and am trying to confirm that a view renders a particular partial in my test. 我有一个运行rspec-rails 2.14.0的rails 3.2.13应用程序,我正在尝试确认视图在我的测试中呈现特定的部分。 It actually does work, but I need to add this test. 确实有效,但我需要添加此测试。 Here's what I have so far: 这是我到目前为止所拥有的:

require 'spec_helper'

describe 'users/items/index.html.haml' do
  let(:current_user) { mock_model(User) }

  context 'when there are no items for this user' do
    items = nil

    it 'should render empty inventory partial' do
      response.should render_template(:partial => "_empty_inventory")
    end

  end
end

This runs without error, but does not pass. 这运行没有错误,但没有通过。 The failure is: 失败的是:

Failure/Error: response.should render_template(:partial => "_empty_inventory")
   expecting partial <"_empty_inventory"> but action rendered <[]>

Thanks for any ideas. 谢谢你的任何想法。

EDIT 编辑

This works for me, but Peter's solution is better... 这对我有用,但彼得的解决方案更好......

context 'when there are no items for this user' do

  before do
    view.stub(current_user: current_user)
    items = nil
    render
  end

  it 'should render empty inventory partial' do
    view.should render_template(:partial => "_empty_inventory")
  end

end 

For some reason it was counter-intuitive to me to have to call render on a view, but there you go... 出于某种原因,我必须在视图上调用render ,这是违反直觉的,但是你去...

So the way one usually tests whether a particular partial is rendered in a view spec is by testing the actual content of the partial. 因此,通常测试特定部分是否在视图规范中呈现的方式是测试部分的实际内容。 For example, assume that your _empty_inventory parial has the message 'There is no inventory'. 例如,假设您的_empty_inventory parial具有“没有库存”消息。 Then you might have a spec like: 然后你可能有一个像:

  it "displays the empty inventory message" do
    render
    rendered.should_not have_content('There is no inventory')
  end

Alternately, you could use a controller spec, in which case you need to call the 'render_views' method when setting up the spec. 或者,您可以使用控制器规范,在这种情况下,您需要在设置规范时调用“render_views”方法。 Then you can do something similar to 然后你可以做类似的事情

it 'should render empty inventory partial' do
  get :index, :user_id => user.id
  response.should render_template(:partial => "_empty_inventory")
end

Assuming you've set up the state for the contoller spec. 假设您已为控制器规范设置状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM