Wednesday, April 01, 2015

ruby - Testing STDOUT output in Rspec - Stack Overflow

ruby - Testing STDOUT output in Rspec - Stack Overflow



I am trying to build a spec for this statement. It is easy with 'puts'
print "'#{@file}' doesn't exist: Create Empty File (y/n)?"
expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr
out, err = capture_io do
  my_method
end

assert_equals "my message", out
assert_equals "my error", err
The code below is no longer required, unless you work with Rspec < 3.0 or a different framework.

This code here will allow you to capture whatever is sent to stdout and stderr, respectively:
require 'stringio'

def capture_stdout(&blk)
  old = $stdout
  $stdout = fake = StringIO.new
  blk.call
  fake.string
ensure
  $stdout = old
end

def capture_stderr(&blk)
  old = $stderr
  $stderr = fake = StringIO.new
  blk.call
  fake.string
ensure
  $stderr = old
end
Now when you have a method that should print something to the console
def my_method
  # ...
  print "my message"
end
you can now write a spec like this:
it 'should print "my message"' do
  printed = capture_stdout do
    my_method # do your actual method call
  end

  printed.should eq("my message")
end