Skip to content

Instantly share code, notes, and snippets.

@phoet
Created December 16, 2016 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phoet/b1e211cc5f36dbbc318d25237264c778 to your computer and use it in GitHub Desktop.
Save phoet/b1e211cc5f36dbbc318d25237264c778 to your computer and use it in GitHub Desktop.
Helper to have temporary environment variables (ENV), ie for testing.
# In order to make testing of environment variables easier,
# you can use this helper to temporarily change the ENV to something you expect.
#
# As an example:
#
# Imagine you have some ENV variable that changes based on the current runtime environment.
#
# def user_id
# ENV['TEST_USER_ID'].present? ? ENV['TEST_USER_ID'] : session[:user_id]
# end
#
# Then in your test it would be used like
#
# it 'should return the test-user-id when it is passed through the env' do
# ENV.with_env('TEST_USER_ID' => '123') do
# user_id.must_equal('123')
# end
# end
ENV.define_singleton_method(:with_env) do |new_env, &block|
old_env = to_hash
clear
update(new_env)
begin
block.call
ensure
clear
update(old_env)
end
end
if __FILE__ == $0
require 'minitest/autorun'
describe ENV do
it 'should have the defined arguments only in the scope of the block' do
old_env = ENV.to_hash
ENV.with_env('hi' => 'there') do
ENV['hi'].must_equal('there')
end
ENV.to_hash.must_equal(old_env)
end
it 'should not have existing arguments in the scope of the block' do
ENV['predefined'] = 'yes'
ENV.with_env('hi' => 'there') do
ENV['predefined'].must_equal(nil)
end
ENV['predefined'].must_equal('yes')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment