2019-07-25 05:27:42 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-06-27 13:00:10 +00:00
|
|
|
# Inspired by https://github.com/ljkbennett/stub_env/blob/master/lib/stub_env/helpers.rb
|
2017-01-09 17:19:48 +00:00
|
|
|
module StubENV
|
2017-06-27 13:00:10 +00:00
|
|
|
def stub_env(key_or_hash, value = nil)
|
|
|
|
init_stub unless env_stubbed?
|
2018-01-11 16:34:01 +00:00
|
|
|
|
2017-06-27 13:00:10 +00:00
|
|
|
if key_or_hash.is_a? Hash
|
|
|
|
key_or_hash.each { |k, v| add_stubbed_value(k, v) }
|
|
|
|
else
|
|
|
|
add_stubbed_value key_or_hash, value
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
STUBBED_KEY = '__STUBBED__'.freeze
|
|
|
|
|
|
|
|
def add_stubbed_value(key, value)
|
2017-01-09 17:19:48 +00:00
|
|
|
allow(ENV).to receive(:[]).with(key).and_return(value)
|
2017-12-11 17:52:07 +00:00
|
|
|
allow(ENV).to receive(:key?).with(key).and_return(true)
|
2017-06-27 13:00:10 +00:00
|
|
|
allow(ENV).to receive(:fetch).with(key).and_return(value)
|
2019-01-24 13:43:02 +00:00
|
|
|
allow(ENV).to receive(:fetch).with(key, anything) do |_, default_val|
|
2017-06-27 13:00:10 +00:00
|
|
|
value || default_val
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def env_stubbed?
|
|
|
|
ENV[STUBBED_KEY]
|
2017-01-09 17:19:48 +00:00
|
|
|
end
|
2017-06-24 04:01:32 +00:00
|
|
|
|
2017-06-27 13:00:10 +00:00
|
|
|
def init_stub
|
|
|
|
allow(ENV).to receive(:[]).and_call_original
|
2017-12-11 17:52:07 +00:00
|
|
|
allow(ENV).to receive(:key?).and_call_original
|
2017-06-27 13:00:10 +00:00
|
|
|
allow(ENV).to receive(:fetch).and_call_original
|
|
|
|
add_stubbed_value(STUBBED_KEY, true)
|
2017-06-24 04:01:32 +00:00
|
|
|
end
|
|
|
|
end
|