我的代码只需要在特定版本的 ActiveRecord 上运行(解决旧 AR 库上的错误的方法)。此代码测试 ActiveRecord::VERSION 常量的值以查看它是否需要运行。
有没有办法在 rspec 中模拟这些常量,这样我就可以测试该代码路径,而无需在测试机器上安装正确的 ActiveRecord gem?
最佳答案
我最终编写了一个辅助方法来让我在执行代码块时覆盖常量:
def with_constants(constants, &block)
constants.each do |constant, val|
Object.const_set(constant, val)
end
block.call
constants.each do |constant, val|
Object.send(:remove_const, constant)
end
end
将此代码放入您的 spec_helper.rb 文件后,可以按如下方式使用:
with_constants :RAILS_ROOT => "bar", :RAILS_ENV => "test" do
code goes here ...
end
希望这对你有用。
关于ruby - 我可以使用 rspec 模拟来 stub 版本常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1698335/