سؤال

I made this code and i try to test it with minitest, but it seems that i am not using the right syntax for an exception :/

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

Output :

Run options: --seed 30510

Running tests:

..E

Finished tests in 0.001000s, 3000.0000 tests/s, 2000.0000 assertions/s.

1) Error: test_0002_can_t_divide_by_zero_and_raise_bla(my test): RuntimeError: bla essai.rb:9:in my_method' essai.rb:19:intest_0002_can_t_divide_by_zero_and_raise_bla'

3 tests, 2 assertions, 0 failures, 1 errors, 0 skips

The second test raise me an error, can somebody help me ?

هل كانت مفيدة؟

المحلول

You should call must_raise on proc, not on method call result:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top