Skip to content

Instantly share code, notes, and snippets.

@jazzytomato
Last active April 3, 2024 00:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jazzytomato/79bb6ff516d93486df4e14169f4426af to your computer and use it in GitHub Desktop.
Save jazzytomato/79bb6ff516d93486df4e14169f4426af to your computer and use it in GitHub Desktop.
Simple method to mock environment variable in ruby with minitest or other testing framework
# in test_helper.rb (for example)
def mock_env(partial_env_hash)
old = ENV.to_hash
ENV.update partial_env_hash
begin
yield
ensure
ENV.replace old
end
end
# usage
mock_env('MY_ENV_VAR' => 'Hello') do
assert something?
end
@oliwoodsuk
Copy link

Nice, I just modified it a bit so I can test methods that use Rails.env.production? etc and added defaults.

def mock_enviroment(env: "test", partial_env_hash: {})
  old_env_mode = Rails.env
  old_env = ENV.to_hash
	
  Rails.env = env
  ENV.update(partial_env_hash)
	
  begin
    yield
  ensure
     Rails.env = old_env_mode
     ENV.replace(old_env)
  end
end


# usage
# mock_enviroment(env:"production", partial_env_hash:{"SECRET"=>"123"}) do
#   assert something?
# end

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