[英]How to test controller with Rspec - #show action
我有一個belongs_to
用戶的批處理模型。 用戶應該只能看到自己的Batches實例。
對於index
操作,這是我做的:
Batch#index
context "GET index" do
it "should get only users batches" do
FactoryGirl.create(:batch)
batch = FactoryGirl.create(:batch)
batch2 = FactoryGirl.create(:batch)
subject.current_user.batches << batch
get "index"
assigns(:batches).should == subject.current_user.batches
assigns(:batches).should_not include(batch2)
end
end
對於create
動作,這是我做的:
Batch#create
context "POST create" do
it "should save a users batch into current_user" do
batch = subject.current_user.batches.build(name: 'bla')
put :create, batch
subject.current_user.batches.should include(batch)
end
it "should save a batch from other user into current_user" do
batch = subject.current_user.batches.build(name: 'bla')
batch2 = FactoryGirl.create(:batch)
put :create, batch
subject.current_user.batches.should_not include(batch2)
end
end
但是,我不確定如何在show
動作中測試此行為。 這是我正在做的事情:
Batch#show
context "GET show/:id" do
it "should show batches from user" do
batch_params = FactoryGirl.build(:batch)
batch = subject.current_user.batches.create(batch_params)
get :show, id: batch.id
response.should redirect_to(batch)
end
it "should not show batches from other users" do
batch = subject.current_user.batches.create(name: 'bla')
batch2 = FactoryGirl.create(:batch)
get :show, id: batch2.id
response.should redirect_to(:batches)
end
end
我遇到了以下失敗:
Failures:
1) BatchesController GET show/:id should not show batches from other users
Failure/Error: response.should redirect_to(:batches)
Expected response to be a <:redirect>, but was <200>
# ./spec/controllers/batches_controller_spec.rb:66:in `block (3 levels) in <top (required)>'
2) BatchesController GET show/:id should show batches from user
Failure/Error: batch = subject.current_user.batches.create(batch_params)
NoMethodError:
undefined method `stringify_keys' for #<Batch:0x00000005d0ef80>
# ./spec/controllers/batches_controller_spec.rb:58:in `block (3 levels) in <top (required)>'
我究竟做錯了什么? 我該如何測試view
操作的這種行為?
get :show, id: batch.id
將不會重定向它將呈現顯示,因此響應代碼200,您可以檢查
response.should render_template :show
第一次失敗,“不應該顯示來自其他用戶的批次”,看起來它可能反映了控制器中的實際問題。 您是否也在瀏覽器中對此進行了測試以確認問題是在您的測試中而不是在實際代碼中?
在另一個測試中,我不太確定問題究竟是什么,但我可能會像這樣構建批處理:
batch = FactoryGirl.create(:batch, user: subject.current_user)
嘗試一下,看看它是否解決了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.