更改数据库的 Rspec 操作

发布于 2024-11-05 07:46:55 字数 1038 浏览 1 评论 0原文

我对涉及影响数据库的控制器方法的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

假装不在乎 2024-11-12 07:46:55

我想指出,在控制器规范中测试模型状态并不是一个很好的做法,因为它违反了单元测试的隔离性。您应该测试控制器响应是否适合当前场景。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文