gpt4 book ai didi

ruby-on-rails - 如何使用 Rspec 测试 Controller - #show action

转载 作者:行者123 更新时间:2023-11-28 19:46:59 26 4
gpt4 key购买 nike

我有一个 belongs_to 用户的 Batch 模型。用户应该只能看到他们自己的 Batches 实例。

对于 index 操作,这是我所做的:

批量#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 操作,这是我所做的:

批处理#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 操作中测试此行为。这是我正在做的:

批处理#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 

关于ruby-on-rails - 如何使用 Rspec 测试 Controller - #show action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15433271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com