[rspec-users] Can you control $stdout when specs are running?

David Chelimsky dchelimsky at gmail.com
Wed Jan 12 13:42:00 EST 2011

On Jan 12, 2011, at 9:52 AM, Chuck Remes wrote:

> On Sep 30, 2010, at 10:06 AM, GregD wrote:
>> Hi all,
>> I'm testing java classed using rspec and jruby.  The java super class
>> is trapping an exception and sending a custom message to stdout along
>> with the original exception meaasage.  The original exception is a
>> SAXParseException, if that really matters.  Well, my test is to see if
>> the child object class can handle a garbled XML message a certain
>> way.   The test passes, but I get the nasty java exception stuff that
>> is being sent to stdout when the tests are running, yuk.  I tried
>> closing and opening stdout before and after that particular test and
>> that did not work or I did it wrong.  And I'm not sure this is
>> desirable if the test fails.   Any ideas on this other than to replace
>> the java with ruby or have the java not to dump to stdout?  ;-)   Both
>> of which, I can not do.  But, I can live with the nastiness of this,
>> if there is no possible way around it.
> I'd like to bump this message because I am facing a similar situation. 
> What's a good technique for spec'ing code that prints to STDOUT yet keeps the spec output nice and clean?

I prefer to avoid printing directly to STDOUT, and pass in an IO object to the constructor of the object doing the printing.

class Foo
  def initialize(output=$stdout)
    @output = output

  def do_something_that_prints
    @output.puts "blah, de blah"

Now implementation code can just use a Foo.new, but specs can use a Foo.new(output) where output is a StringIO, stub, whatever.

Make sense?

More information about the rspec-users mailing list