[英]Rspec - Test that rails view renders a specific partial
我有一个运行rspec-rails 2.14.0的rails 3.2.13应用程序,我正在尝试确认视图在我的测试中呈现特定的部分。 它确实有效,但我需要添加此测试。 这是我到目前为止所拥有的:
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
,这是违反直觉的,但是你去...
因此,通常测试特定部分是否在视图规范中呈现的方式是测试部分的实际内容。 例如,假设您的_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
假设您已为控制器规范设置状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.