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.
我正在为ruby程序创建一个测试文件,该程序可以找到给定数字的阶乘。我的所有测试都运行良好,除了我的字符串错误和负数测试应该引发异常。我不完全确定引发异常的语法,我已经阅读了文档。
this is my code for the factorial program itself, n is the number thats supposed to be passed:
这是我的阶乘程序本身的代码,n是应该传递的数字:
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?
我的两个测试都会以错误的形式返回,而我的其他3个测试正常的数字则会以错误的方式返回。我是ruby的新手但是我想在assert_raise之后想要传递,因为我的实际错误信息在我的析法程序中吗?
1 个解决方案
#1
0
in your first test case, it will not return an error because -1
is also considered as an Integer
在第一个测试用例中,它不会返回错误,因为-1也被视为整数
#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)
#1
0
in your first test case, it will not return an error because -1
is also considered as an Integer
在第一个测试用例中,它不会返回错误,因为-1也被视为整数
#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)