我制作了这段代码,我尝试用minitest测试它,但似乎我没有使用正确的语法来表示异常:/
def my_method(a,b=10)
begin
a/b
rescue
raise 'bla'
end
end
describe 'my test' do
it "must divide" do
my_method(6,3).must_equal(2)
end
it "can't divide by zero and raise bla" do
my_method(6,0).must_raise 'bla'
end
it "must divide by 10 if there is only one arg" do
my_method(10).must_equal(1)
end
end
输出
运行选项: - 种子30510
正在运行测试:
..ë
完成测试0.001000s,3000.0000次测试/秒,2000.0000断言/秒。
1)错误: test_0002_can_t_divide_by_zero_and_raise_bla(我的测试): RuntimeError:bla essai.rb:9:在
my_method' essai.rb:19:in
test_0002_can_t_divide_by_zero_and_raise_bla'3次测试,2次断言,0次失败,1次错误,0次跳过
第二次测试给我一个错误,有人能帮帮我吗?
答案 0 :(得分:8)
你应该在proc上调用must_raise
,而不是在方法调用结果上调用:
require 'minitest/autorun'
def my_method(a,b=10)
begin
a/b
rescue
raise 'bla'
end
end
describe 'my test' do
it "must divide" do
my_method(6,3).must_equal(2)
end
it "can't divide by zero and raise bla" do
div_by_zero = lambda { my_method(6,0) }
div_by_zero.must_raise RuntimeError
error = div_by_zero.call rescue $!
error.message.must_equal 'bla'
end
it "must divide by 10 if there is only one arg" do
my_method(10).must_equal(1)
end
end