StdioTrap lets you capture stdout, stderr at runtime, e.g. for inspection inside a unit-test. It can also fake stdin.
require 'stdiotrap'
describe StdioTrap do
describe 'Inline usage' do
it "captures stdout and stderr" do
trapped = StdioTrap.capture {
puts "Hello world!"
$stderr.puts "Hello other world!"
}
trapped[:stdout].should == "Hello world!\n"
trapped[:stderr].should == "Hello other world!\n"
end
end
describe 'Common rspec usage' do
before :each do
StdioTrap.trap!
end
after :each do
StdioTrap.release!
end
it "captures stdout and stderr" do
puts "Hello world!"
$stderr.puts "Hello other world!"
StdioTrap.stdout.should == "Hello world!\n"
StdioTrap.stderr.should == "Hello other world!\n"
end
end
end
For more usage examples please refer to the spec suite.
StdioTrap is based on this code snippet (bottom of page) by Ng Tze Yang