Open Synapse

Hi, I'm Abhay Kumar. I like to throw up interesting things I encounter here. You can also see the result of my mustache pact with my coworkers, check out what I'm up to or see the few photos I take. I like to receive email and instant messages (AIM / Jabber), as well. Some links of interest: Calais Text Tagger, Powerset

Feb 18
Permalink

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…

Comments (View)
blog comments powered by Disqus

Change CongressVote Obama