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

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'))

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.


As Heroku suggests, you can use Foreman's .env file to store environment variables for development.

If you do that, you can use foreman run to run your specs:

foreman run bundle exec rspec spec