How to change the environment variable of rails in testing
Gmail Example Instead use the Ruby variable ENV["GMAIL_USERNAME"] to obtain an environment variable. The variable can be used anywhere in a Rails application. Ruby will replace ENV["GMAIL_USERNAME"] with an environment variable. Let's consider how to set local environment variables.
Rails reads the current environment from the operating system's environment variables by checking the following in order of priority: Get the value of the RAILS_ENV environment variable by calling ENV["RAILS_ENV"] If the above is nil, then get ENV["RACK_ENV"] If the above is nil, then make it equal to "development"
An environment variable is a key/value pair, it looks like this: KEY=VALUE. We use these variables to share configuration options between all the programs in your computer. That's why it's important to learn how they work & how to access them from your Ruby programs using the ENV special variable.
You could do
Rails.stub(env: ActiveSupport::StringInquirer.new("production"))
Then Rails.env
, Rails.development?
etc will work as expected.
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"))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With