Module: Test::Unit::Util::Output

Included in:
TestCase
Defined in:
lib/test/unit/util/output.rb

Instance Method Summary collapse

Instance Method Details

#capture_output ⇒ Object Also known as: capture_io

Returns output for standard output and standard error as string.

Calls from multiple threads are serialized. Note that output written by other threads while the block is running is also captured. Don't call #capture_output in another thread or fiber while the block is running. It blocks or raises ThreadError.

Example:

capture_output do
  puts("stdout")
  warn("stderr")
end # -> ["stdout\n", "stderr\n"]


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/test/unit/util/output.rb', line 23

def capture_output
  require "stringio"

  capture_output_monitor.synchronize do
    output = StringIO.new
    error = StringIO.new
    stdout_save, stderr_save = $stdout, $stderr
    $stdout, $stderr = output, error
    begin
      yield
      [output.string, error.string]
    ensure
      $stdout, $stderr = stdout_save, stderr_save
    end
  end
end