0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#Ruby の #Rspec ENV 環境変数を他のテストケースを汚さずにハッシュで上書きして特定のキーを削除する ( overwrite hash clean not dirty by stub constant and delete specific key )

Last updated at Posted at 2020-04-18

# 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

チャットメンバー募集

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

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?