2019-04-11 08:02:24 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-01-23 05:23:23 -05:00
|
|
|
# Inspired by https://github.com/ljkbennett/stub_env/blob/master/lib/stub_env/helpers.rb
|
2019-02-11 04:04:59 -05:00
|
|
|
module Helpers
|
2018-01-23 05:23:23 -05:00
|
|
|
module StubENV
|
|
|
|
def stub_env(key_or_hash, value = nil)
|
|
|
|
init_stub unless env_stubbed?
|
|
|
|
|
|
|
|
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)
|
|
|
|
allow(ENV).to receive(:[]).with(key).and_return(value)
|
|
|
|
allow(ENV).to receive(:key?).with(key).and_return(true)
|
|
|
|
allow(ENV).to receive(:fetch).with(key).and_return(value)
|
2019-01-24 08:43:02 -05:00
|
|
|
allow(ENV).to receive(:fetch).with(key, anything) do |_, default_val|
|
2018-01-23 05:23:23 -05:00
|
|
|
value || default_val
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def env_stubbed?
|
|
|
|
ENV[STUBBED_KEY]
|
|
|
|
end
|
|
|
|
|
|
|
|
def init_stub
|
|
|
|
allow(ENV).to receive(:[]).and_call_original
|
|
|
|
allow(ENV).to receive(:key?).and_call_original
|
|
|
|
allow(ENV).to receive(:fetch).and_call_original
|
2018-06-09 00:41:42 -04:00
|
|
|
# Prevent secrets from leaking in CI
|
|
|
|
allow(ENV).to receive(:inspect).and_return([])
|
2018-01-23 05:23:23 -05:00
|
|
|
add_stubbed_value(STUBBED_KEY, true)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|