Skip to content

Commit

Permalink
Merge pull request #2632 from rspec/add-isolated-env-for-rake
Browse files Browse the repository at this point in the history
Add support for running Rake task in a clean environment
  • Loading branch information
JonRowe committed Jun 12, 2019
2 parents c408a2a + 3950e4f commit 2800fe1
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Changelog.md
Expand Up @@ -15,6 +15,8 @@ Enhancements:
(Viktor Fonic, #2634)
* Issue warning when invalid values are used for `RSpec::Configuration#fail_fast`
(Viktor Fonic, #2634)
* Add support for running the Rake task in a clean environment.
(Jon Rowe, #2632)

Bug Fixes:

Expand Down
22 changes: 21 additions & 1 deletion lib/rspec/core/rake_task.rb
Expand Up @@ -45,6 +45,21 @@ class RakeTask < ::Rake::TaskLib
# A message to print to stderr when there are failures.
attr_accessor :failure_message

if RUBY_VERSION < "1.9.0" || Support::Ruby.jruby?
# Run RSpec with a clean (empty) environment is not supported
def with_clean_environment=(_value)
raise ArgumentError, "Running in a clean environment is not supported on Ruby versions before 1.9.0"
end

# Run RSpec with a clean (empty) environment is not supported
def with_clean_environment
false
end
else
# Run RSpec with a clean (empty) environment.
attr_accessor :with_clean_environment
end

# Use verbose output. If this is set to true, the task will print the
# executed spec command to stdout. Defaults to `true`.
attr_accessor :verbose
Expand Down Expand Up @@ -76,7 +91,12 @@ def run_task(verbose)
command = spec_command
puts command if verbose

return if system(command)
if with_clean_environment
return if system({}, command, :unsetenv_others => true)
else
return if system(command)
end

puts failure_message if failure_message

return unless fail_on_error
Expand Down
18 changes: 18 additions & 0 deletions spec/rspec/core/rake_task_spec.rb
Expand Up @@ -148,6 +148,24 @@ def silence_output(&block)
end
end

context "with_clean_environment is set" do
it "removes the environment variables", :if => RUBY_VERSION >= '1.9.0', :unless => RSpec::Support::Ruby.jruby? do
with_env_vars 'MY_ENV' => 'ABC' do
if RSpec::Support::OS.windows?
essential_shell_variables = /\["ANSICON", "ANSICON_DEF", "HOME", "TMPDIR", "USER"\]/
else
essential_shell_variables = /\["PWD"(?:, "SHLVL")?(?:, "_")?(?:, "__CF_USER_TEXT_ENCODING")?\]/
end

expect {
task.with_clean_environment = true
task.ruby_opts = '-e "puts \"Environment: #{ENV.keys}\""'
task.run_task false
}.to avoid_outputting.to_stderr.and output(essential_shell_variables).to_stdout_from_any_process
end
end
end

def loaded_files
args = Shellwords.split(spec_command)
args -= [task.class::RUBY, "-S", task.rspec_path]
Expand Down

0 comments on commit 2800fe1

Please sign in to comment.