Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to write specs for code that depends on environment variables?

I am testing some code that pulls its configuration from environment variables (set by Heroku config vars in production, for local development I use foreman).

What's the best way to test this kind of code with RSpec?

I came up with this:

before :each do     ENV.stub(:[]).with("AWS_ACCESS_KEY_ID").and_return("asdf")     ENV.stub(:[]).with("AWS_SECRET_ACCESS_KEY").and_return("secret") end 

If you don't need to test different values of the environment variables, I guess you could set them in spec_helper instead.

like image 548
Luke Francl Avatar asked Mar 08 '12 00:03

Luke Francl


People also ask

What is the correct format for an environment variable name?

Environment variable names used by the utilities in the Shell and Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase letters, digits, and the '_' (underscore) from the characters defined in Portable Character Set and do not begin with a digit.

How do you display environment variables?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

How do developers use environment variables?

Environment variables provide a good way to set application execution parameters that are used by processes that you do not have direct control over. However, environment variables should not be used for configuration values within your own dynamic applications. Environment variables are global variables.


2 Answers

You also can stub the constant:

stub_const('ENV', {'AWS_ACCESS_KEY_ID' => 'asdf'}) 

Or, if you still want the rest of the ENV:

stub_const('ENV', ENV.to_hash.merge('AWS_ACCESS_KEY_ID' => 'asdf')) 
like image 164
iGEL Avatar answered Oct 08 '22 13:10

iGEL


That would work.

Another way would be to put a layer of indirection between your code and the environment variables, like some sort of configuration object that's easy to mock.

like image 41
nicholaides Avatar answered Oct 08 '22 14:10

nicholaides