🖥

#Ruby の #Rspec ENV 環境変数を他のテストケースを汚さずにハッシュで上書きして特定のキーを削除する ( overwrite

2023/09/01に公開

# run
#
# FOO=bar rspec this-spec-file.rb

describe do
  # OK
  describe do
    it do
      expect(ENV.fetch("FOO")).to eq "bar"
    end
  end

  # OK
  # it does not make dirty ENV ( overwritten in another test cases )
  describe do
    # Actually ENV is not hash but mock by Hash
    before do
      stub_const "ENV", ENV.to_h.tap {|env| env.delete("FOO") }
    end

    it do
      expect(ENV["FOO"]).to eq nil
    end

    # KeyError: key not found: "FOO"
    it do
      expect { ENV.fetch("FOO") }.to raise_error(KeyError)
    end
  end

  # OK
  describe do
    it do
      expect(ENV.fetch("FOO")).to eq "bar"
    end
  end
end


# is expected to eq "bar"

# is expected to raise KeyError

# is expected to eq "bar"

# Finished in 0.00387 seconds (files took 0.12889 seconds to load)
# 3 examples, 0 failures

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3080

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2020-04-18

Discussion