【发布时间】:2021-05-09 10:43:10
【问题描述】:
TL;DR - 我的 ruby 类可以读取现实生活中的 ENV 变量。 Rspec 示例可以读取模拟的 ENV var。但是我的 ruby 类在测试中无法读取相同的模拟 ENV var。我做错了什么?
全文:
我有这个 ruby 类,它使用(可选)ENV var 来设置用户的风格,默认为“香草”:
class MyConfigger
attr_reader :flavor
def load_config
@flavor = ENV['MY_FLAVOR'] || 'vanilla'
self
end
end
这很有效,在 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"
但是,当我对其运行测试时,它看不到模拟的 ENV var。前两个按预期通过,但最后一个失败,表明我的应用代码没有看到模拟的 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
我尝试了 许多 ENV['MY_FLAVOR'] 与 ENV.fetch('MY_FLAVOR', 'vanilla') 等的变体,但没有一个成功。
我错过了什么?
【问题讨论】:
标签: ruby rspec mocking environment-variables