Added another realization for capturing output #161

Closed
wants to merge 1 commit into
from
View
@@ -440,23 +440,38 @@ def assert_throws sym, msg = nil
#
# out, err = capture_io do
# warn "You did a bad thing"
+ # puts "Some info"
# end
#
+ # even in subprocesses:
+ #
+ # out, err = full_capture_io do
+ # system("echo 'You did a bad thing' 1>&2")
+ # system("echo 'Some info'")
+ # end
+ #
# assert_match %r%bad%, err
+ # assert_match %r%info%, out
def capture_io
- require 'stringio'
+ require 'tempfile'
- orig_stdout, orig_stderr = $stdout, $stderr
- captured_stdout, captured_stderr = StringIO.new, StringIO.new
- $stdout, $stderr = captured_stdout, captured_stderr
+ stdout, stderr = Tempfile.new(""), Tempfile.new("")
+ orig_stdout, orig_stderr = $stdout.dup, $stderr.dup
+ $stdout.reopen(stdout)
+ $stderr.reopen(stderr)
yield
- return captured_stdout.string, captured_stderr.string
+ $stdout.rewind
+ $stderr.rewind
+ return $stdout.read, $stderr.read
ensure
- $stdout = orig_stdout
- $stderr = orig_stderr
+ stdout.unlink
+ stderr.unlink
+
+ $stdout.reopen(orig_stdout)
+ $stderr.reopen(orig_stderr)
end
##
@@ -1181,6 +1181,14 @@ def test_capture_io
assert_equal "hi\n", out
assert_equal "bye!\n", err
+
+ out, err = capture_io do
+ system("echo 'hi'")
+ system("echo 'bye!' 1>&2")
+ end
+
+ assert_equal "hi\n", out
+ assert_equal "bye!\n", err
ensure
$VERBOSE = orig_verbose
end