Created
September 10, 2012 21:36
-
-
Save route/3694068 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/spec' | |
require 'minitest/autorun' | |
describe "Capture" do | |
it "should capture all output in the same process" do | |
out, err = capture_io do | |
puts "STDOUT" | |
warn "STDERR" | |
end | |
assert_equal "STDOUT\n", out | |
assert_equal "STDERR\n", err | |
end | |
# This test isn't capture output and get failure | |
it "should capture all output in subprocess" do | |
out, err = capture_io do | |
system("echo 'STDOUT'") | |
system("echo 'STDERR' 1>&2") | |
end | |
assert_equal "STDOUT\n", out | |
assert_equal "STDERR\n", err | |
end | |
it "should capture all output in subprocess with new method" do | |
out, err = new_capture_io do | |
system("echo 'STDOUT'") | |
system("echo 'STDERR' 1>&2") | |
end | |
assert_equal "STDOUT\n", out | |
assert_equal "STDERR\n", err | |
end | |
# I think we can replace `capture_io` | |
# or add another realization | |
def new_capture_io | |
require 'tempfile' | |
stdout, stderr = Tempfile.new(""), Tempfile.new("") | |
orig_stdout, orig_stderr = STDOUT.dup, STDERR.dup | |
STDOUT.reopen(stdout) | |
STDERR.reopen(stderr) | |
yield | |
STDOUT.rewind | |
STDERR.rewind | |
return STDOUT.read, STDERR.read | |
ensure | |
stdout.unlink | |
stderr.unlink | |
STDOUT.reopen(orig_stdout) | |
STDERR.reopen(orig_stderr) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@route you can use StringIO instead of Tempfile to avoid disk IO.