Module: Wrong::Helpers

Included in:
MiniTest::Unit::TestCase, Wrong, Wrong
Defined in:
lib/wrong/helpers.rb

Instance Method Summary collapse

Instance Method Details

#capturing(*streams) ⇒ Object

Usage: capturing { puts “hi” } => “hin” capturing(:stderr) { $stderr.puts “hi” } => “hin” out, err = capturing(:stdout, :stderr) { … }

see www.justskins.com/forums/closing-stderr-105096.html for more explanation



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/wrong/helpers.rb', line 21

def capturing(*streams)
  streams = [:stdout] if streams.empty?
  original = {}
  captured = {}

  # reassign the $ variable (which is used by well-behaved code e.g. puts)
  streams.each do |stream|
    original[stream] = (stream == :stdout ? $stdout : $stderr)
    captured[stream] = StringIO.new
    reassign_stream(stream, captured)
  end

  yield

  # return either one string, or an array of two strings
  if streams.size == 1
    captured[streams.first].string
  else
    [captured[streams[0]].string, captured[streams[1]].string]
  end

ensure

  streams.each do |stream|
    # bail if stream was reassigned inside the block
    if (stream == :stdout ? $stdout : $stderr) != captured[stream]
      raise "#{stream} was reassigned while being captured"
    end
    # support nested calls to capturing
    original[stream] << captured[stream].string if original[stream].is_a? StringIO
    reassign_stream(stream, original)
  end
end

#rescuingObject

Executes a block that is expected to raise an exception. Returns that exception, or nil if none was raised.



5
6
7
8
9
10
11
12
13
# File 'lib/wrong/helpers.rb', line 5

def rescuing
  error = nil
  begin
    yield
  rescue Exception, RuntimeError => e
    error = e
  end
  error
end