debian-mirror-gitlab/spec/support/helpers/stub_env.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
1.4 KiB
Ruby
Raw Normal View History

2019-10-12 21:52:04 +05:30
# frozen_string_literal: true
2017-09-10 17:25:29 +05:30
# Inspired by https://github.com/ljkbennett/stub_env/blob/master/lib/stub_env/helpers.rb
2017-08-17 22:00:37 +05:30
module StubENV
2023-04-23 21:23:45 +05:30
# Stub ENV variables
#
# You can provide either a key and value as separate params or both in a Hash format
#
# Keys and values will always be converted to String, to comply with how ENV behaves
#
# @param key_or_hash [String, Hash<String,String>]
# @param value [String]
2017-09-10 17:25:29 +05:30
def stub_env(key_or_hash, value = nil)
init_stub unless env_stubbed?
2018-03-17 18:26:18 +05:30
2017-09-10 17:25:29 +05:30
if key_or_hash.is_a? Hash
2023-04-23 21:23:45 +05:30
key_or_hash.each do |key, value|
add_stubbed_value(key, ensure_env_type(value))
end
2017-09-10 17:25:29 +05:30
else
2023-04-23 21:23:45 +05:30
add_stubbed_value key_or_hash, ensure_env_type(value)
2017-09-10 17:25:29 +05:30
end
end
private
2021-04-29 21:17:54 +05:30
STUBBED_KEY = '__STUBBED__'
2017-09-10 17:25:29 +05:30
def add_stubbed_value(key, value)
2017-08-17 22:00:37 +05:30
allow(ENV).to receive(:[]).with(key).and_return(value)
2018-03-17 18:26:18 +05:30
allow(ENV).to receive(:key?).with(key).and_return(true)
2017-09-10 17:25:29 +05:30
allow(ENV).to receive(:fetch).with(key).and_return(value)
2019-03-02 22:35:43 +05:30
allow(ENV).to receive(:fetch).with(key, anything) do |_, default_val|
2017-09-10 17:25:29 +05:30
value || default_val
end
end
def env_stubbed?
ENV[STUBBED_KEY]
end
def init_stub
allow(ENV).to receive(:[]).and_call_original
2018-03-17 18:26:18 +05:30
allow(ENV).to receive(:key?).and_call_original
2017-09-10 17:25:29 +05:30
allow(ENV).to receive(:fetch).and_call_original
add_stubbed_value(STUBBED_KEY, true)
2017-08-17 22:00:37 +05:30
end
2023-04-23 21:23:45 +05:30
def ensure_env_type(value)
value.nil? ? value : value.to_s
end
2017-08-17 22:00:37 +05:30
end