Question

I'm creating a testing file for a ruby program that finds factorials of given numbers. All of my tests run well except I get an error with my string and negative number tests that should raise exceptions. I'm not entirely sure of the syntax for raise exception, I've read the docs.

this is my code for the factorial program itself, n is the number thats supposed to be passed:

if n.is_a?(Integer) == false
raise 'strings are not acceptable'
end


if n < 0
raise 'negatives are not acceptable'
end

the test case in my test file are as follows:

def test_negative
factorial(-1)
assert_raise do
end
end

def test_string
factorial('hello')
assert_raise do
end
end

both of my tests come back as errors while my other 3, that test normal numbers, come back as passed. I'm new to ruby but I would just want a pass after assert_raise do as my actual error message is in my factorial program right?

Was it helpful?

Solution

in your first test case, it will not return an error because -1 is also considered as an Integer

#irb output
2.0.0-p247 :003 > a = -1
 => -1 
2.0.0-p247 :004 > a.is_a?(Integer)
 => true 

and in your second case, when you pass a string, it will error even before going inside your condition as you are trying to compare string with an integer

#irb outout
2.0.0-p247 :007 > "hello" < 0
ArgumentError: comparison of String with 0 failed
    from (irb):7:in `<'
    from (irb):7

and off topic, you could write

if n.is_a?(Integer) == false
  raise 'strings are not acceptable'
end

as (more ruby way :))

raise 'strings are not acceptable' unless n.is_a?(Integer)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top