Redirecting $stdout for fun and profit
I was looking at Tom’s Chronic library and noticed this little bit of overridden code where he adds an extra space after every call to Object#p:
alias p_orig p
def p(val)
p_orig val
puts
end
It made me wonder how someone would write a test to cover this code and I remembered another post Tom wrote a while ago. Instead of redirecting the code to /dev/null, it’s possible to redirect it to an IO object and then check the object after the call.
describe Object, :p do
it "prints things out" do
old_stdout = $stdout.dup
tempio = StringIO.new
$stdout = tempio
p "foo"
$stdout = old_stdout
tempio.string.should == "\"hello world\"\n\n"
end
end
Ruby really is awesome…

