在测试过程中更改 Rails 环境 [英] change rails environment in the mid of testing
问题描述
测试中如何更改rails的环境变量
How to change the environment variable of rails in testing
推荐答案
You can do
Rails.stub(env: ActiveSupport::StringInquirer.new("production"))
然后 Rails.env
、Rails.development?
等将按预期工作.
Then Rails.env
, Rails.development?
etc will work as expected.
使用 RSpec 3 或更高版本,您可能希望使用新的零猴子修补"语法(如@AnkitG 在另一个答案中提到的)以避免弃用警告:
With RSpec 3 or later you may want to use the new "zero monkeypatching" syntax (as mentioned by @AnkitG in another answer) to avoid deprecation warnings:
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("production"))
我通常在规范帮助器中定义一个 stub_env
方法,这样我就不必将所有这些东西都放在我的测试中.
I usually define a stub_env
method in a spec helper so I don't have to put all that stuff inline in my tests.
考虑的选项(如此处的评论中所建议)而是依赖一些更有针对性的配置,您可以在环境文件中设置这些配置并在测试中进行更改.
An option to consider (as suggested in a comment here) is to instead rely on some more targeted configuration that you can set in your environment files and change in tests.
这篇关于在测试过程中更改 Rails 环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!