Skip to content

Commit ea5de88

Browse files
authored
Merge pull request #504 from bkeepers/autorestore-stubbed
Fix: "can't modify frozen Hash" when stubbing ENV
2 parents e9c1907 + 6a12390 commit ea5de88

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

lib/dotenv/diff.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,10 @@ def any?
5050
private
5151

5252
def snapshot
53-
ENV.to_h.freeze
53+
# `dup` should not be required here, but some people use `stub_const` to replace ENV with
54+
# a `Hash`. This ensures that we get a frozen copy of that instead of freezing the original.
55+
# https://github.com/bkeepers/dotenv/issues/482
56+
ENV.to_h.dup.freeze
5457
end
5558
end
5659
end

spec/dotenv_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,15 @@
336336
Dotenv.instance_variable_set(:@diff, nil)
337337
expect { Dotenv.restore }.not_to raise_error
338338
end
339+
340+
it "can save and restore stubbed ENV" do
341+
stub_const("ENV", ENV.to_h.merge("STUBBED" => "1"))
342+
Dotenv.save
343+
ENV["MODIFIED"] = "1"
344+
Dotenv.restore
345+
expect(ENV["STUBBED"]).to eq("1")
346+
expect(ENV["MODIFED"]).to be(nil)
347+
end
339348
end
340349

341350
describe "modify" do

0 commit comments

Comments
 (0)