[rspec-users] Testing console IO / Re: Selectively ignoring exceptions in examples

Alex Chaffee alex at stinky.com
Tue Aug 30 14:24:36 EDT 2011

> I've found this pattern useful as now that only files in my bin/ folder ever access ARGV, STDOUT etc, the code is more loosely coupled, but also I can see exactly where I'm talking to the outside world. Every time I want to send some output, I think- "Should I really be giving this object a StreamBundle? Is it really appropriate for it to be talking to the user directly?"

I hear you. When I first started coding in Ruby I was injecting all
over the place. But nowadays I'm much more comfortable with the
flexibility of things like reopening classes during tests, or mocking
methods, or resetting globals...

...or grabbing and reassigning $stdout and $stderr, which is what
"capturing" does.

The basic idea is that Ruby is *already* decoupled from stdin/out/err
via its dynamic nature and $globals. I get that by naming the inputs
explicitly you're ensuring 100% compliance but you should consider
whether it's worth it. Passing around DI clumps (aka "value objects"
or "parameter objects" in some circles) can make your code a lot less
concise, and concision is one of the great joys of Ruby.

btw apologies if you already know this, but inside a normal Ruby
program you should always use $stderr/$stdout/$stdin, not
STDERR/STDOUT/STDIN since the former are settable and the latter are
hardcoded to the "real" streams and, as true CONSTANTS, not easy to
change. For whatever reason I see the caps versions used a lot more
than the dollar versions, which is a shame.

Alex Chaffee - alex at stinky.com

More information about the rspec-users mailing list