Skip to content

Instantly share code, notes, and snippets.

@route
Created September 10, 2012 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save route/3694068 to your computer and use it in GitHub Desktop.
Save route/3694068 to your computer and use it in GitHub Desktop.
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
@sobrinho
Copy link

@route you can use StringIO instead of Tempfile to avoid disk IO.

@route
Copy link
Author

route commented Sep 11, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment