From 8f13c1ebd9671058a878b21ce3f40d255e8591df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Coutable?= Date: Tue, 27 Jun 2017 15:00:10 +0200 Subject: [PATCH] Use a slightly cleaner approach to stub ENV MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rémy Coutable --- spec/support/stub_env.rb | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/spec/support/stub_env.rb b/spec/support/stub_env.rb index 2999bcd9fb1..b8928867174 100644 --- a/spec/support/stub_env.rb +++ b/spec/support/stub_env.rb @@ -1,15 +1,33 @@ +# Inspired by https://github.com/ljkbennett/stub_env/blob/master/lib/stub_env/helpers.rb module StubENV - def stub_env(key, value) - allow(ENV).to receive(:[]).and_call_original unless @env_already_stubbed - @env_already_stubbed ||= true - allow(ENV).to receive(:[]).with(key).and_return(value) + 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 -end -# It's possible that the state of the class variables are not reset across -# test runs. -RSpec.configure do |config| - config.after(:each) do - @env_already_stubbed = nil + private + + STUBBED_KEY = '__STUBBED__'.freeze + + def add_stubbed_value(key, value) + allow(ENV).to receive(:[]).with(key).and_return(value) + allow(ENV).to receive(:fetch).with(key).and_return(value) + allow(ENV).to receive(:fetch).with(key, anything()) do |_, default_val| + 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(:fetch).and_call_original + add_stubbed_value(STUBBED_KEY, true) end end