Unit test an output with puts

Hi,

I want to be able to unit/test an output with the method ‘puts’. Here’s
a small example of what I’m trying to achieve:

#-------8<--------
class Foo
def output
puts “bar”
end
end
#-------8<--------

…and in my test

#-------8<--------
require ‘unit/test’

def test_output
myFoo = Foo.new
assert_equal(“bar”, myFoo.output)
end
#-------8<--------

The problem is that the ‘puts’ method returns nil and I don’t know how
to catch the output.

Thanks in advance.

Hi Eric,
I’d do this with a mock object. With Mocha I’d do something like this:

myFoo.expects(:puts).with(“bar”)

The idea is that you don’t really want to capture the output (you know
puts works) you just want to make sure it’s called properly.

You may need to define a fake puts method in Foo to make this work. So
in your test:

class Foo
def puts(*args)
end
end

class TestCase…
end

Eric B. wrote:

I want to be able to unit/test an output with the method ‘puts’. Here’s
a small example of what I’m trying to achieve:

puts is a convenience function. It’s really $stdout.write() etc.

So use fileHandle.write(), and then pass in a handle to an IO-stream, or
a
temporary file, into your routine.

Yes, that means you pass more crap around. Unit testing powerfully
decouples
your code, such that you no longer couple even with convenience objects
like
$stdout.

On 9/8/06, Eric H. [email protected] wrote:

Use util_capture from the ZenTest gem. You get two StringIO objects
back from calling util_capture that hold the contents of $stdout and
$stderr in the block:

 out, err = util_capture do
   Foo.new.output
 end

Nice. Does this also prevent the output from being dumped to the
console during the test?


Regards,
John W.

On Sep 9, 2006, at 12:38 PM, John W. wrote:

console during the test?
Yes.


Eric H. - [email protected] - http://blog.segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com

Thanks everybody and thanks to Eric, this is exactly what I needed.

On Sep 8, 2006, at 12:29 PM, Eric B. wrote:

I want to be able to unit/test an output with the method ‘puts’.
Here’s
a small example of what I’m trying to achieve:

Use util_capture from the ZenTest gem. You get two StringIO objects
back from calling util_capture that hold the contents of $stdout and
$stderr in the block:

require ‘test/unit’
require ‘rubygems’
require ‘test/zentest_assertions’

class Foo
def output
puts “bar”
end
end

class TestFoo < Test::Unit::TestCase

def test_output
out, err = util_capture do
Foo.new.output
end

 assert_equal "bar\n", out.string
 assert_equal "", err.string

end
end


Eric H. - [email protected] - http://blog.segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com