Skip to content

Instantly share code, notes, and snippets.

@harigopal
Last active November 27, 2019 10:05
Show Gist options
  • Save harigopal/236681889272aa084ffe8a05df2f8ef4 to your computer and use it in GitHub Desktop.
Save harigopal/236681889272aa084ffe8a05df2f8ef4 to your computer and use it in GitHub Desktop.
A small helper method that temporarily changes environment variables in specs. It's an alternative to the ClimateControl rubygem that feels more like RSpec.
# A tiny RSpec helper
#
# spec/support/helpers/let_env.rb
module LetEnv
def let_env(name)
around do |example|
@original_environment_vars ||= {}
@original_environment_vars[name] ||= ENV[name.to_s]
ENV[name.to_s] = yield
example.run
ENV[name.to_s] = @original_environment_vars[name]
end
end
end
# Setup
require_relative 'support/helpers/let_env.rb'
Rspec.configure do |config|
config.extend LetEnv
end
# Usage
let_env(:ENV_VAR) { 'temporary value' }
after(:all) do
# Back to original value.
puts ENV['ENV_VAR']
end
it 'will read temporary_value' do
expect(ENV['ENV_VAR']).to eq('temporary value')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment