2013-11-04 79 views
4

我有一个运行rspec-rails 2.14.0的rails 3.2.13应用程序,我试图确认视图在我的测试中呈现特定的部分。它实际上确实工作,但我需要添加此测试。这是我到目前为止:Rspec - 测试轨道视图呈现特定的部分

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 

这运行没有错误,但没有通过。失败是:

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

感谢您的任何想法。

编辑

这对我的作品,但彼得的解决方案是更好的... ...

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 

出于某种原因,这是反直觉我有打电话给render上来看,但你去...

+0

这是什么类型的?它看起来像是一个视图规范,但没有渲染调用。它使用一个'响应'对象,这是一个控制器规范的指示。 –

+0

这是一个视图规范,你是对的。我试图从我找到的不同代码拼凑代码。我在文档中没有看到任何明显的内容:https://www.relishapp.com/rspec/rspec-rails/v/2-8/docs/view-specs/view-spec – panzhuli

回答

7

所以人们通常测试一个特定的部分是否在视图规范渲染的方式是通过测试部分的实际内容。例如,假设您的_empty_inventory parial有消息“没有库存”。那么你可能有一个像规格:

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

或者,你可以使用一个控制器规范,在这种情况下你建立规范时需要调用“render_views”的方法。然后你可以做类似于

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

假设你已经设置了控制器规范的状态。

+0

我认为一些问题是我不想要控制器中的逻辑,但也许它不应该在视图中。 – panzhuli

+0

在rspec文件中,是否有任何方法只渲染一个部分,然后检查呈现的内容是否存在于特定的dom中? –