rspec STDOUT

I happened to write some rspec for one ruby program which was accepting some input text in some form, and then it was expected to print the output to the console, or perhaps I did not want to separate the logic of printing. Anyways, that made me expect rspec should check the console output of my program, and after some googling(thanks to many rubyist) I got to work the following


require 'spec_helper'
describe "Transaction" do
it "should handle dummy numerals" do
transaction_input(%{
x1 is I
x5 is V
x10 is X
x50 is L
x100 is C
x500 is D
x1000 is M
how much is x1000 x100 ?
how much is x1 x1 ?
how much is x1 x5 ?
}
).should_output(%{
x1000 x100 is 1100
x1 x1 is 2
x1 x5 is 4
})
end
end

Wow, I liked it.

And the spec_helper made it for me


require "#{File.dirname(__FILE__)}/../lib/transactions.rb"
include Transactions
def capture_stdout(&block)
original_stdout = $stdout
$stdout = fake = StringIO.new
begin
yield
ensure
$stdout = original_stdout
end
fake.string
end
class TransactionInput
def initialize output
@output = output
end
def should_output output
@output.split("\n").should == output.split("\n")[1..-2].collect{|line| line.strip}
end
end
def transaction_input input
TransactionInput.new capture_stdout{ input.split("\n")[1..-2].each{|line| Message.new(line).process} }
end

view raw

spec_helper.rb

hosted with ❤ by GitHub

Advertisement

One thought on “rspec STDOUT

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s