From 6a12390cc630e8969382ee663915ae158fe88137 Mon Sep 17 00:00:00 2001 From: Brandon Keepers Date: Mon, 6 May 2024 14:43:40 -0400 Subject: [PATCH] Fix: "can't modify frozen Hash" when stubbing ENV --- lib/dotenv/diff.rb | 5 ++++- spec/dotenv_spec.rb | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/dotenv/diff.rb b/lib/dotenv/diff.rb index 329473b3..0085c40c 100644 --- a/lib/dotenv/diff.rb +++ b/lib/dotenv/diff.rb @@ -50,7 +50,10 @@ def any? private def snapshot - ENV.to_h.freeze + # `dup` should not be required here, but some people use `stub_const` to replace ENV with + # a `Hash`. This ensures that we get a frozen copy of that instead of freezing the original. + # https://github.com/bkeepers/dotenv/issues/482 + ENV.to_h.dup.freeze end end end diff --git a/spec/dotenv_spec.rb b/spec/dotenv_spec.rb index 08e7cb9e..363a10c9 100644 --- a/spec/dotenv_spec.rb +++ b/spec/dotenv_spec.rb @@ -336,6 +336,15 @@ Dotenv.instance_variable_set(:@diff, nil) expect { Dotenv.restore }.not_to raise_error end + + it "can save and restore stubbed ENV" do + stub_const("ENV", ENV.to_h.merge("STUBBED" => "1")) + Dotenv.save + ENV["MODIFIED"] = "1" + Dotenv.restore + expect(ENV["STUBBED"]).to eq("1") + expect(ENV["MODIFED"]).to be(nil) + end end describe "modify" do