我应该在 Rails 控制器测试中模拟我的模型吗?

发布于 2024-08-12 06:10:44 字数 522 浏览 5 评论 0原文

我在我的报道中发现了漏洞,因为我一直在控制器示例中嘲笑我的模型。当我删除控制器所依赖的模型方法时,我不会遇到失败。

来自静态类型语言的 TDD,我总是会模拟对测试对象的依赖关系,这些对象会访问数据库以提高速度。在上面的例子中我仍然会失败,因为我的模拟子类化了原始对象。我正在寻找动态语言的最佳实践。

谢谢。

更新:

在对此提出了很多相互矛盾的意见之后,似乎可以归结为你认同哪种哲学。

Rspec 社区似乎采用大量存根依赖项来实现测试对象的隔离。验收测试(传统上称为集成测试;)用于确保您的对象与其运行时依赖项一起工作。

shoulda / Test::Unit 社区似乎尽可能远离存根。这允许您的测试确认被测对象确实与其依赖项一起工作。

该视频很好地总结了这一点:http://vimeo.com/3296561

I am finding holes in my coverage because I have been mocking my models in controller examples. When I remove a model's method upon which a controller depends, I do not get a failure.

Coming from TDD in statically typed languages, I would always mock dependencies to the object under test that hit the database to increase speed. I would still get failures in the above example, since my mocks subclassed the original object. I am looking for best practices in a dynamic language.

Thanks.

UPDATE:

After getting a lot of conflicting opinions on this, it seems it boils down to which philosophy you buy into.

The Rspec community appears to embrace heavily stubbing dependencies to achieve isolation of the object under test. Acceptance tests (traditionally known as integration tests ;) are used to ensure your objects work with their runtime dependencies.

The shoulda / Test::Unit community appears to stay away from stubbing as much as possible. This allows your tests to confirm your object under test actually works with its dependencies.

This video summarizes this nicely: http://vimeo.com/3296561

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

贪了杯 2024-08-19 06:10:44

是的,在您的控制器示例中,模拟您的模型。在您的模型示例中,测试您的模型。

Yes, in your controller examples, mock your models. In your model examples, test your models.

浅唱々樱花落 2024-08-19 06:10:44

如果您使用 Mocha,则应执行以下操作。

Mocha::Configuration.prevent(:stubbing_non_existent_method)

If you're using Mocha, the following should do it.

Mocha::Configuration.prevent(:stubbing_non_existent_method)
七分※倦醒 2024-08-19 06:10:44

在编写单元测试时,整个目标应该是仅测试该单元。将模型视为一个单元并单独覆盖它。模型的更改不应直接影响控制器的单元测试覆盖率。

While writing unit tests, the whole aim should be test that unit only. Consider Model as one unit and cover it separately. Change in Model should not directly impact unit test coverage of controller.

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