Stubbing ENV variables with RSpec in Ruby on Rails

You can do this with RSpec:Mocks’s allow, receive, and with methods, like so:

allow[ENV].to receive(:[]).with("variable_to_stub")

You’re also likely to run into the following error:

Please stub a default value first if message might be received with other args as well.

This happens when your app calls other ENV values which have not been stubbed. To fix this, use the and_call_original method to return their original values.

NOTE: Make sure to call and_call_original before the stubbed ENV variable.

# call the non-stubbed `ENV` variables as usual
allow[ENV].to receive(:[]).and_call_original 

# stub the given `ENV` variable
allow[ENV].to receive(:[]).with("variable_to_stub")