Hi all,
I'm a newbie to Ruby. I tried the below code but don't understand why
the "test_typecheck" does not give any error. Could someone shed a light
to my problem ?
thanks
tony
test1.rb
···
========
require 'test/unit'
class SimpleNumber
def initialize( num )
raise "input must be a number" unless num.is_a?(Numeric) @x = num
end
def add( y ) @x + y
end
def multiply( y ) @x * y
end
end
#error = SimpleNumber.new('abc') <== this raises exeption
class TestSimpleNumber < Test::Unit::TestCase
def test_simple
assert_equal(4, SimpleNumber.new(2).add(2) )
assert_equal(4, SimpleNumber.new(2).multiply(2) )
end
def test_typecheck
assert_raise( RuntimeError ) { SimpleNumber.new('abc') }
end
end
=====================
I would expect to see assertion failure for test_typecheck but it does
not give any.
output
Run options:
# Running tests:
..
Finished tests in 0.006836s, 292.5688 tests/s, 438.8531 assertions/s.
On Sun, Apr 29, 2012 at 6:35 PM, Thi N. <lists@ruby-forum.com> wrote:
Hi all,
I'm a newbie to Ruby. I tried the below code but don't understand why
the "test_typecheck" does not give any error. Could someone shed a light
to my problem ?
thanks
tony
test1.rb
require 'test/unit'
class SimpleNumber
def initialize( num )
raise "input must be a number" unless num.is_a?(Numeric) @x = num
end
def add( y ) @x + y
end
def multiply( y ) @x * y
end
end
#error = SimpleNumber.new('abc') <== this raises exeption
class TestSimpleNumber < Test::Unit::TestCase
def test_simple
assert_equal(4, SimpleNumber.new(2).add(2) )
assert_equal(4, SimpleNumber.new(2).multiply(2) )
end
def test_typecheck
assert_raise( RuntimeError ) { SimpleNumber.new('abc') }
end
end
=====================
I would expect to see assertion failure for test_typecheck but it does
not give any.
output
Run options:
# Running tests:
..
Finished tests in 0.006836s, 292.5688 tests/s, 438.8531 assertions/s.
I would expect to see assertion failure for test_typecheck but it does
not give any.
Why do you expect to see assertion failure?
As far as I can see, SimpleNumber.new('abc') raises a RuntimeError, and
you're catching it with assert_raise(RuntimeError), i.e. you're
correctly testing that your code raises an error.