Skip to content
This repository has been archived by the owner on Nov 30, 2024. It is now read-only.

Commit

Permalink
Reassign $stdout/$stderr in CaptureStreamToTempfile
Browse files Browse the repository at this point in the history
Otherwise it doesn't work when $stderr has previously been reassigned,
like in the rspec-core test suite
  • Loading branch information
jdelStrother committed Sep 20, 2024
1 parent 3671eb5 commit 392050b
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/rspec/matchers/built_in/output.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def to_stderr
# Works when subprocesses print to stdout as well.
# This is significantly (~30x) slower than `to_stdout`
def to_stdout_from_any_process
@stream_capturer = CaptureStreamToTempfile.new("stdout", STDOUT) # rubocop:disable Style/GlobalStdStream
@stream_capturer = CaptureStreamToTempfile.new("stdout")
self
end

Expand All @@ -55,7 +55,7 @@ def to_stdout_from_any_process
# Works when subprocesses print to stderr as well.
# This is significantly (~30x) slower than `to_stderr`
def to_stderr_from_any_process
@stream_capturer = CaptureStreamToTempfile.new("stderr", STDERR) # rubocop:disable Style/GlobalStdStream
@stream_capturer = CaptureStreamToTempfile.new("stderr")
self
end

Expand Down Expand Up @@ -213,7 +213,7 @@ def capture(block)
end

# @private
class CaptureStreamToTempfile < Struct.new(:name, :stream)
class CaptureStreamToTempfile < Struct.new(:name)
def capture(block)
# We delay loading tempfile until it is actually needed because
# we want to minimize stdlibs loaded so that users who use a
Expand All @@ -223,19 +223,29 @@ def capture(block)
# thread, fileutils, etc), so it's worth delaying it until this point.
require 'tempfile'

original_stream = stream.clone
stream = name == 'stdout' ? STDOUT : STDERR # rubocop:ignore Style/GlobalStdStream
captured_stream = Tempfile.new(name)

begin
if name == 'stdout'
$stdout = captured_stream
else
$stderr = captured_stream
end
captured_stream.sync = true
stream.reopen(captured_stream)
block.call
captured_stream.rewind
captured_stream.read
ensure
stream.reopen(original_stream)
stream.reopen(stream)
captured_stream.close
captured_stream.unlink
if name == 'stdout'
$stdout = stream
else
$stderr = stream
end
end
end
end
Expand Down

0 comments on commit 392050b

Please sign in to comment.