Add with_env helper to set temporary ENV vars
This commit is contained in:
parent
4ca2efb12d
commit
30adcab6cf
@ -270,4 +270,30 @@ describe "globally-scoped helper methods" do
|
||||
}.to raise_error(MethodDeprecatedError, %r{method.*replacement.*homebrew/homebrew-core.*homebrew/core}m)
|
||||
end
|
||||
end
|
||||
|
||||
describe "#with_env" do
|
||||
it "sets environment variables within the block" do
|
||||
expect(ENV["PATH"]).not_to eq("/bin")
|
||||
with_env "PATH" => "/bin" do
|
||||
expect(ENV["PATH"]).to eq("/bin")
|
||||
end
|
||||
end
|
||||
|
||||
it "restores ENV after the block" do
|
||||
with_env "PATH" => "/bin" do
|
||||
expect(ENV["PATH"]).to eq("/bin")
|
||||
end
|
||||
expect(ENV["PATH"]).not_to eq("/bin")
|
||||
end
|
||||
|
||||
it "restores ENV if an exception is raised" do
|
||||
expect {
|
||||
with_env "PATH" => "/bin" do
|
||||
raise StandardError, "boom"
|
||||
end
|
||||
}.to raise_error(StandardError)
|
||||
|
||||
expect(ENV["PATH"]).not_to eq("/bin")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@ -533,3 +533,27 @@ def migrate_legacy_keg_symlinks_if_necessary
|
||||
end
|
||||
FileUtils.rm_rf legacy_pinned_kegs
|
||||
end
|
||||
|
||||
# Calls the given block with the passed environment variables
|
||||
# added to ENV, then restores ENV afterwards.
|
||||
# Example:
|
||||
# with_env "PATH" => "/bin" do
|
||||
# system "echo $PATH"
|
||||
# end
|
||||
#
|
||||
# Note that this method is *not* thread-safe - other threads
|
||||
# which happen to be scheduled during the block will also
|
||||
# see these environment variables.
|
||||
def with_env(hash)
|
||||
old_values = {}
|
||||
begin
|
||||
hash.each do |key, value|
|
||||
old_values[key] = ENV.delete(key)
|
||||
ENV[key] = value
|
||||
end
|
||||
|
||||
yield if block_given?
|
||||
ensure
|
||||
ENV.update(old_values)
|
||||
end
|
||||
end
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user