diff --git a/lib/dotenv.rb b/lib/dotenv.rb index 007692a1..1d4edaa6 100644 --- a/lib/dotenv.rb +++ b/lib/dotenv.rb @@ -74,6 +74,9 @@ def save # @param env [Hash] Hash of keys and values to restore, defaults to the last saved state # @param safe [Boolean] Is it safe to modify `ENV`? Defaults to `true` in the main thread, otherwise raises an error. def restore(env = @diff&.a, safe: Thread.current == Thread.main) + # No previously saved or provided state to restore + return unless env + diff = Dotenv::Diff.new(b: env) return unless diff.any? diff --git a/spec/dotenv_spec.rb b/spec/dotenv_spec.rb index 8c121a44..08e7cb9e 100644 --- a/spec/dotenv_spec.rb +++ b/spec/dotenv_spec.rb @@ -325,6 +325,17 @@ end.join expect(ENV["MODIFIED"]).to eq("true") end + + it "is a noop if nil state provided" do + expect { Dotenv.restore(nil) }.not_to raise_error + end + + it "is a noop if no previously saved state" do + # Clear state saved in setup + expect(Dotenv.instance_variable_get(:@diff)).to be_instance_of(Dotenv::Diff) + Dotenv.instance_variable_set(:@diff, nil) + expect { Dotenv.restore }.not_to raise_error + end end describe "modify" do