我可以使用 rspec 模拟来消除版本常量吗?
我的代码只需要在特定版本的 ActiveRecord 上运行(旧 AR 库上的错误的解决方法)。此代码测试 ActiveRecord::VERSION 常量的值以查看是否需要运行。
有没有办法在 rspec 中模拟这些常量,以便我可以测试该代码路径,而无需依赖在测试机器上安装正确的 ActiveRecord gem?
I've got code that only needs to run on a certain version of ActiveRecord (a workaround for a bug on old AR libraries). This code tests the values of ActiveRecord::VERSION constants to see if it needs to be run.
Is there a way to mock out those constants in rspec so I can test that code path without relying on having the right ActiveRecord gem installed on the test machine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我最终编写了一个帮助器方法,让我在执行代码块时覆盖常量:
将此代码放入您的 spec_helper.rb 文件后,可以按如下方式使用它:
希望这对您有用。
I ended up writing a helper method to let me override constants while executing a block of code:
After putting this code in your spec_helper.rb file, it can be used as follows:
Hope this works for you.
在 RSpec 2.11 中,
stub_const
支持开箱即用的常量存根:有关更多详细信息,请参阅 Myron Marston 的公告:
With RSpec 2.11, constant stubbing is supported out of the box with
stub_const
:See Myron Marston's announcement for more details:
德鲁·奥尔森(Drew Olson),我采纳了你的想法并做了一些修改以添加范围:
将此代码放入 specs/support/with_constants.rb 文件后,可以按如下方式使用:
Drew Olson, I took your idea and made a few modifications to add scoping:
After putting this code at specs/support/with_constants.rb file, it can be used as follows:
添加救援块对于确保测试套件中其他测试的恢复恒定非常重要!
通常
Add rescue block is important for ensure restore constant for another tests in test suite !
Typically