Skip to content

Instantly share code, notes, and snippets.

@weavenet
Created August 7, 2013 05:07
Show Gist options
  • Save weavenet/6171363 to your computer and use it in GitHub Desktop.
Save weavenet/6171363 to your computer and use it in GitHub Desktop.
Ruby method to stub out ENV variables in Rspec.
module EnvVar
def set_env_var(name, value)
ENV.stub(:[])
ENV.stub(:[]).with(name).and_return(value)
end
end
@chrishough
Copy link

How did you get this working with Rspec 3.5?

@briancain
Copy link

@chrishough You just need to update the function to stub like this:

allow(ENV).to receive(:[]).with(name).and_return(value)

@aldrienht
Copy link

Seems the function only accepts 1 env variable, tried to have 2, and the first one got overwritten ...?

@lucia-w
Copy link

lucia-w commented Sep 5, 2020

Have you try these ways:

stub_const('ENV', ENV.to_hash.merge('HOST' => 'http://sample.host'))

stub_const('ENV', 'HOST' => 'www.aaa.com')

@marciojg
Copy link

@aldrienht Try this:

allow(ENV).to receive(:[]).with(name, second_param).and_return(value)

@pboling
Copy link

pboling commented Jan 31, 2023

The climate_control gem is great for this use case, if you only need to support Ruby >= 2.5.

The stub_env or rspec-stubbed_env gems provide this functionality for both older and newer rubies.

@henrik
Copy link

henrik commented Feb 23, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment