Skip to content

Instantly share code, notes, and snippets.

@Kosmas
Created November 4, 2015 10:14
Show Gist options
  • Save Kosmas/3b67ed6ceac5db7da1a7 to your computer and use it in GitHub Desktop.
Save Kosmas/3b67ed6ceac5db7da1a7 to your computer and use it in GitHub Desktop.
test_helper.rb
require './test/additional_assertions'
additional_assertions.rb
module AdditionalAssertions
module CaptureOutput
# NOTE: MiniTest has capture_io and capture_subprocess_io
# so when upgraded to MiniTest this should be replaced
# with MiniTest methods
# Use as:
# out = capture_output { method_to_call(param1, param2) }
# output = out[0], error = out[1] or
# output = out.first, error = out.last
def capture_output
require 'stringio'
captured_stdout, captured_stderr = StringIO.new, StringIO.new
orig_stdout, orig_stderr = $stdout, $stderr
$stdout, $stderr = captured_stdout, captured_stderr
begin
yield
ensure
$stdout = orig_stdout
$stderr = orig_stderr
end
return captured_stdout.string, captured_stderr.string
end
def capture_subprocess_output
require 'tempfile'
captured_stdout, captured_stderr = Tempfile.new("out"), Tempfile.new("err")
orig_stdout, orig_stderr = $stdout.dup, $stderr.dup
$stdout.reopen captured_stdout
$stderr.reopen captured_stderr
begin
yield
$stdout.rewind
$stderr.rewind
[captured_stdout.read, captured_stderr.read]
ensure
captured_stdout.unlink
captured_stderr.unlink
$stdout.reopen orig_stdout
$stdout.reopen orig_stderr
end
end
end
include CaptureOutput
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment