From: Eric Hodel Date: 2006-03-09T07:57:47+09:00 Subject: Re: assert_raise question On Mar 8, 2006, at 1:42 PM, Sean Carley wrote: > Currently, assert_raise expects you to know exactly what kind of > exception > is going to be thrown by raise. Basically it tests to see if > exception.class == > expected.class. > > I think a more appropriate behavior would be to test > exception.kind_of?expected. I would also be happy if there were > one method that performed the way it does currently and another > that checks exception parentage. For a given input a method should only raise one class of exception. The restriction forces you to write better tests. > Please see the code below for an example of two tests. I think > both should > pass but only the first test does because ArgumentError != > StandardError. require 'socket' require 'test/unit' class MyClass def connect(overthere) unless overthere =~ /:\d+\Z/ then raise ArgumentError, "Use host:port, got #{overthere}" end host, port = overthere.split ':' @socket = TCPSocket.new host, port.to_i end end This method can raise at least two different exceptions on bad input so you should test for them separately. This allows consumers of your code to behave properly depending upon what arguments they feed your code. class TestMyClass < Test::Unit::TestCase def setup @obj = MyClass.new end def test_connect_bad_args_no_port assert_raises ArgumentError do @obj.connect 'host' end end def test_connect_bad_args_bad_port assert_raises ArgumentError do @obj.connect 'host:port' end end def test_connect_bad_host assert_raises SocketError do @obj.connect 'no-such-host.example.com:80' end end end -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com