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

Ash Moran ash.moran at patchspace.co.uk
Tue Aug 30 06:20:53 EDT 2011


On 30 Aug 2011, at 00:09, Alex Chaffee wrote:

> I do. So often that I wrote a helper and put it in Wrong.

Cool, and also… I really should try Wrong! I've just put it on my project TODO list as something to investigate

> I don't quite get what "stream_bundle.captured_error" is in your
> example, but I think the above example would become
> 
> rescuing {
>  run_command(%w[ missing_wallet.dat ])
> }.message.should == "Couldn't find whatever"
> 
> We've also got "capturing" for grabbing console output, e.g.
> 
> capturing { puts "hi" }.should == "hi"

Sorry, I didn't realise how opaque that is if you don't know what one is.

Basically, I wanted to decouple the app from STDIN/STDOUT/STDERR so I started injecting StringIO objects around for testing. After a while I had a data clump of @input/@output/@error in classes everywhere, so I made a StreamBundle[1] to encapsulate them. (Apologies for lack of syntax highlighting on patch-tag.com)

But then I realised my tests were making a `StreamBundle.new(StringIO.new, StringIO.new, StringIO.new)` everywhere, so I factored out the duplication into a CapturingStreamBundle[2] decorator that records all output to secondary StringIO objects. Now I just call `CapturingStreamBundle.test_bundle` to get one.

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?"

That's the backstory anyway!

Ash

[1] https://patch-tag.com/r/ashmoran/rbcoin/snapshot/current/content/pretty/lib/bitcoin/console/stream_bundle.rb
[2] https://patch-tag.com/r/ashmoran/rbcoin/snapshot/current/content/pretty/lib/bitcoin/console/capturing_stream_bundle.rb

-- 
http://www.patchspace.co.uk/
http://www.linkedin.com/in/ashmoran



More information about the rspec-users mailing list