在不加载环境或使用数据库的情况下运行 Rails 单元测试
作为一项学术练习,我想我应该尝试在不加载 Rails env(或访问数据库)的情况下运行我的单元测试。
我以前见过这样做的,而且似乎人们对它的讨论已经足够多了,但我找不到任何好的/当前的资源来完成它。
有没有人有关于如何做到这一点的任何好故事或一篇不错的长博客文章?
As something of an academic exercise, I thought I'd try to get my unit tests running without loading the Rails env (or hitting the database).
I've seen this done before, and it seems like folks talk about it enough, but I can't find any good/current resources on getting it done.
Does anyone have any good stories or a nice long blog post about how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个有用的链接:在没有 Rails 的情况下测试 Rails
没有数据库的测试将涉及很多模拟和存根,没有什么特别要添加的。
An useful link: testing Rails without Rails
Testing without database would involve much mocks & stubs, nothing special to add.
查看 NullDB。我在这方面取得了好坏参半的成功。
创作者&当前的维护者正在寻求新的维护者加入,因此当前的一些问题应该很快就能得到解决。
Check out NullDB. I've had mixed success with it.
The creator & current maintainer are looking to get a new maintainer in so some of its current issues should be ironed out soon.
编写应用程序的替代方法略有不同。
将您想要测试的所有重要逻辑提取到 ruby 类中,而无需依赖数据库。
只为这些类编写测试 - 你的测试将会成功! :)
例如,
从数据库依赖项中提取“业务逻辑”
现在,模块
CalculateNewOrderTotal
可以通过非常快速的测试完全覆盖,不需要模拟或实际数据库。您仍然可以使用实际数据库为
Customer.create_order
方法编写快乐路径测试。额外的好处
您的业务逻辑独立于持久性框架。
您的业务逻辑独立于持久性模式,您可以更改存储数据的方式,而无需“接触”重要的业务逻辑代码。
不涉及模拟
没有额外的抽象层 - 您仍然可以使用 ActiveRecord 的所有优点,例如使用事务包装调用方法。
不涉及其他框架或 gem - 纯 ruby 和 RSpec 或您选择的测试框架:)
Alternative approach to write application little bit differently.
Extract all important logic you want to test into ruby classes without database dependencies.
Write tests for those classes only - your tests will fly! :)
For example
Extract "business logic" out of database dependencies
Now the module
CalculateNewOrderTotal
can be fully covered with very fast tests which doesn't require mocks or actual database.You can still write happy path tests with actual database for
Customer.create_order
method.Extra benefits
Your business logic is independent of persistence framework.
Your business logic is independent of persistence schema, you can change how to store data without "touching" important business logic code.
No mocks involved
No extra layers of abstractions - you can still use all benefits of the ActiveRecord, for example wrap call of the method with the transaction.
No other frameworks or gems are involved - pure ruby and RSpec or testing framework of your choice :)