[英]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.