Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change rails environment in the mid of testing

How to change the environment variable of rails in testing

like image 905
aswini Avatar asked Nov 24 '10 11:11

aswini


People also ask

What variable changes the environment in Ruby on Rails?

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.

How does Rails know which environment?

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"

What is environment variable rails?

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.


1 Answers

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.

like image 92
Henrik N Avatar answered Sep 19 '22 03:09

Henrik N