Module: Micron::Util::IO

Included in:
Micron
Defined in:
lib/micron/util/io.rb

Instance Method Summary collapse

Instance Method Details

#capture_ioObject

Captures $stdout and $stderr into strings:

out, err = capture_io do
  puts "Some info"
  warn "You did a bad thing"
end

assert_match %r%info%, out
assert_match %r%bad%, err

NOTE: For efficiency, this method uses StringIO and does not capture IO for subprocesses. Use #capture_subprocess_io for that.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/micron/util/io.rb', line 19

def capture_io
  require 'stringio'

  captured_stdout, captured_stderr = StringIO.new, StringIO.new

  # synchronize do
    orig_stdout, orig_stderr = $stdout, $stderr
    $stdout, $stderr         = captured_stdout, captured_stderr

    begin
      yield
    ensure
      $stdout = orig_stdout
      $stderr = orig_stderr
    end

  # end

  return captured_stdout.string, captured_stderr.string
end

#dispose_io(out, err) ⇒ Object

Dispose of STDOUT/STDERR

Parameters:

  • out (Array<IO>)
  • err (Array<IO>)


44
45
46
47
48
49
50
# File 'lib/micron/util/io.rb', line 44

def dispose_io(out, err)
  STDOUT.reopen out.last
  out.last.close
  STDERR.reopen err.last
  err.last.close
  STDOUT.sync = STDERR.sync = true
end