From: Philip Murray Date: 2007-08-08T13:06:59+09:00 Subject: Re: capturing stdout during unit tests --Apple-Mail-149--67075717 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed On 8/08/2007, at 3:59 PM, Mark Slater wrote: > I've written a script for use with Nagios (a monitoring tool) that > I'd like to test. The requirements for the script is that it output > a single line of text to STDOUT and then exit with a status code (0 > - 3). My script is designed to monitor a few different services... > each invocation includes a required command line argument > specifying the service to monitor in the current invocation. To do > that, I created a class for each type of service monitor. > > I'm now writing unit tests for my script, and I'd like to check > that the output written to STDOUT by each service monitor class is > correct. But I'm new to Ruby and I'm not sure how to do that. In > other languages, I'd simply redefine STDOUT as a stream that goes > to a large in-memory buffer, but I haven't seen anything that > suggests that is possible in Ruby. The best I've come up with so > far is creating a temporary file and calling $stdout.reopen() with > the path to that temporary file. However, I'd much rather do this > in memory because then I never have to worry about what file system > and permissions the user executing the unit test has. > > Thanks, > Try this: require 'stringio' $stdout = StringIO.new (This will break in IRB w/ Readline) StringIO has all the IO methods, but acts on a string, not a file. So you should be able to do what you want. Cheers Phil --Apple-Mail-149--67075717--