在测试过程中更改 Rails 环境 [英] change rails environment in the mid of testing

查看:73
本文介绍了在测试过程中更改 Rails 环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试中如何更改rails的环境变量

How to change the environment variable of rails in testing

推荐答案

You can do

Rails.stub(env: ActiveSupport::StringInquirer.new("production"))

然后 Rails.envRails.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆