Skip to content

Instantly share code, notes, and snippets.

@paneq
Created December 11, 2010 16:11
Show Gist options
  • Save paneq/737444 to your computer and use it in GitHub Desktop.
Save paneq/737444 to your computer and use it in GitHub Desktop.
Capturing IO in Ruby
##
# Captures $stdout and $stderr into strings:
#
# out, err = capture_io do
# warn "You did a bad thing"
# end
#
# assert_match %r%bad%, err
def capture_io
require 'stringio'
orig_stdout, orig_stderr = $stdout, $stderr
captured_stdout, captured_stderr = StringIO.new, StringIO.new
$stdout, $stderr = captured_stdout, captured_stderr
yield
return captured_stdout.string, captured_stderr.string
ensure
$stdout = orig_stdout
$stderr = orig_stderr
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment