diff --git a/lib/dotenv/diff.rb b/lib/dotenv/diff.rb index 329473b..0085c40 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 08e7cb9..363a10c 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