Joã*_*iel 6 testing unit-testing rspec ruby-on-rails rspec-rails
我有belongs_to一个用户的批处理模型.用户应该只能看到自己的Batches实例.
对于index行动,这是我做的:
Batch#indexcontext "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
Run Code Online (Sandbox Code Playgroud)
对于create行动,这是我做的:
Batch#createcontext "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
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何在show操作中测试此行为.这是我正在做的事情:
Batch#showcontext "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
Run Code Online (Sandbox Code Playgroud)
我遇到了以下失败:
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)>'
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我该如何测试这种行为view?
get :show, id: batch.id
Run Code Online (Sandbox Code Playgroud)
将不会重定向它将呈现显示,因此响应代码200,您可以检查
response.should render_template :show
Run Code Online (Sandbox Code Playgroud)
第一个失败“不应显示其他用户的批次”,看起来可能反映了控制器中的实际问题。您是否也在浏览器中对此进行了测试,以确认问题是在您的测试中而不是在实际代码中?
在另一个测试中,我不太确定问题到底是什么,但我可能会像这样构建批次:
batch = FactoryGirl.create(:batch, user: subject.current_user)
Run Code Online (Sandbox Code Playgroud)
尝试一下,看看是否不能解决问题。
| 归档时间: |
|
| 查看次数: |
14698 次 |
| 最近记录: |