TL;DR - My ruby class can read an ENV var in real life. Rspec examples can read a mocked ENV var. But my ruby class can't read the same mocked ENV var in tests. What am I doing wrong?
The full story:
I have this ruby class that uses an (optional) ENV var to set a user's flavor, defaulting to 'vanilla':
class MyConfigger
attr_reader :flavor
def load_config
@flavor = ENV['MY_FLAVOR'] || 'vanilla'
self
end
end
This works, as tested in IRB:
% irb -I lib -r my_configger
irb(main):001:0> MyConfigger.new.load_config.flavor
=> "vanilla"
% MY_FLAVOR=cherry irb -I lib -r my_configger
irb(main):001:0> MyConfigger.new.load_config.flavor
=> "cherry"
However, it does not see the mocked ENV var when I run tests on it. The first two pass, as expected, but the last one fails, indicating that my app code is not seeing the mocked ENV var:
RSpec.describe MyConfigger do
let(:config) { described_class.new }
before { config.load_config }
describe '.flavor' do
subject { config.flavor }
context 'with defaults' do
it { is_expected.to eq 'vanilla' }
end
context 'when MY_ENV=chocolate' do
before { allow(ENV).to receive(:[]).with('MY_FLAVOR').and_return('chocolate') }
it "ENV['MY_FLAVOR'] in example is chocolate" do # This test passes.
expect(ENV['MY_FLAVOR']).to eq 'chocolate'
end
it 'config.flavor is chocolate' do # <<---------------- THIS TEST FAILS
is_expected.to eq 'chocolate'
end
end
end
end
MyConfigger
.flavor
with defaults
is expected to eq "vanilla"
when MY_ENV=chocolate
ENV['MY_FLAVOR'] in example is chocolate
config.flavor is chocolate (FAILED - 1)
Failures:
1) MyConfigger.flavor when MY_ENV=chocolate config.flavor is chocolate
Failure/Error: is_expected.to eq 'chocolate'
expected: "chocolate"
got: "vanilla"
(compared using ==)
# ./spec/lib/my_configger_fail_spec.rb:25:in `block (4 levels) in <top (required)>'
3 examples, 1 failure
I've tried many variations of ENV['MY_FLAVOR']
vs ENV.fetch('MY_FLAVOR', 'vanilla')
etc, and none succeeds.
What am I missing?
question from:
https://stackoverflow.com/questions/66057369/rspec-mocked-env-vars-are-visible-in-examples-but-not-in-application-code 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…