更改数据库的 Rspec 操作
我对涉及影响数据库的控制器方法的 rpsec 测试的行为有点困惑。我见过许多涉及 POST 和 DELETE 的 rspec 测试示例,人们在其中检查对象是否已创建或删除。在大多数这些测试中,人们可以通过以下测试来检查数据库中模型的计数是否增加或减少:
delete :clear_photos, :id => @album.id
@album.photos.size.should == 0
或使用 lambda:
lambda {delete :destroy, :id => @photo.id}.should change(@album.photos, :size).by(-1)
最后一个示例中的语法并不完美,但我的观点是,根据我的经验,我需要在对象上调用 reload 才能使这些测试中的任何一个通过,但由于某种原因,其他测试能够使它们工作而无需显式调用 reload。每次我测试数据库创建/销毁操作时调用重新加载对我来说似乎很可疑。
谁能帮助我了解发生了什么事?谢谢!
实际代码更新
it "should clear all photos for an album" do
@album = Factory(:album, :photos => [Factory(:photo), Factory(:photo)])
delete :clear, :album_id => @album.id
@album.photo_count.should == 0
end
我得到这样的回复:
'PhotosController#clear should clear all photos for an album' FAILED
expected: 0,
got: 2 (using ==)
./spec/controllers/photos_controller_spec.rb:17:
如果我在调用 photo_count 之前重新加载@album,它就会起作用。
I'm a bit confused with the behavior of rpsec tests involving controller methods that affect the DB. I have seen many examples of rspec tests that involve POST's and DELETE's where people check to see that an object was created or deleted. In most of these tests people are able to just check that the count of the model in the DB has increased or descreased with a tests such as:
delete :clear_photos, :id => @album.id
@album.photos.size.should == 0
or with lambdas:
lambda {delete :destroy, :id => @photo.id}.should change(@album.photos, :size).by(-1)
The syntax isn't perfect in the last example but my point is that in my experience, I have needed to call reload on the object in order for any of these tests to pass, but for some reason, other are able to make them work without explicitly calling reload. Something about calling reload every time I am testing a db create/destroy action seems fishy to me.
Can anyone help me understand what's going on? Thanks!
ACTUAL CODE UPDATE
it "should clear all photos for an album" do
@album = Factory(:album, :photos => [Factory(:photo), Factory(:photo)])
delete :clear, :album_id => @album.id
@album.photo_count.should == 0
end
I get this response:
'PhotosController#clear should clear all photos for an album' FAILED
expected: 0,
got: 2 (using ==)
./spec/controllers/photos_controller_spec.rb:17:
If I reload the @album before calling photo_count though, it works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想指出,在控制器规范中测试模型状态并不是一个很好的做法,因为它违反了单元测试的隔离性。您应该测试控制器响应是否适合当前场景。
I would like to point out that testing a model state in a controller spec is not a very good practice, because it violates the isolation of a unit test. You should instead test if a controller response is appropriate for the current scenario.