Ruby Unit Testing with Console Output

This example shows how to write unit tests for Ruby code that prints to the console. In many situations, software components can be designed to return a string which is then written to some output by another layer. The code that generated the string can easily be tested by an assertion on the return value given some input. This strategy has another significant advantage in that the output can be redirected without changing the code that generates the string. However, there are times when you're writing simple command line output and you'd just like to have some automated tests to ensure that the program responds in the right way.

This information can be found elsewhere, but I failed at the Internet at some point when I was searching for the best way to do it. It was late at night, and what I came up with at the time was a bizarre system of forking a new process and capturing its IO so I could verify that some puts calls in my code were outputting the right information. The next morning, I looked at what I had written, cried on the inside, and wrote something like the following to let me unit test my console output. (Note: The images link to source code files.)

Here is the code I want to test:

Code to be Tested

And here is a unit test for that code:

Ruby Unit Test

Another way to implement the wrap method:

Alternate Stdout Wrap

That last example is perhaps pointless, but does demonstrate some of the flexibility of Ruby and its support for singleton classes.