-->

什么是在MINITEST的assert_raises / must_raise检查异常消息预期的语法

2019-07-18 10:46发布

什么是在MINITEST的检查异常消息预期的语法assert_raises / must_raise

我试图做一个断言类似以下,其中"Foo"是预期的错误信息:

proc { bar.do_it }.must_raise RuntimeError.new("Foo")

Answer 1:

您可以使用assert_raises断言,或must_raise期望。

it "must raise" do
  assert_raises RuntimeError do 
    bar.do_it
  end
  ->     { bar.do_it }.must_raise RuntimeError
  lambda { bar.do_it }.must_raise RuntimeError
  proc   { bar.do_it }.must_raise RuntimeError
end

如果您需要将错误对象上测试的东西,你可以从断言或期望像这样得到它:

describe "testing the error object" do
  it "as an assertion" do
    err = assert_raises RuntimeError { bar.do_it }
    assert_match /Foo/, err.message
  end

  it "as an exception" do
    err = ->{ bar.do_it }.must_raise RuntimeError
    err.message.must_match /Foo/
  end
end


Answer 2:

要断言异常:

assert_raises FooError do
  bar.do_it
end

要断言异常消息:

按照API文档 , assert_raises返回匹配的,所以你可以检查邮件的例外,属性等。

exception = assert_raises FooError do
  bar.do_it
end
assert_equal('Foo', exception.message)


Answer 3:

MINITEST不提供(还)可以检查实际的异常信息的方式。 但是你可以添加,做它一个辅助方法和扩展ActiveSupport::TestCase类在轨测试套件,例如在任何地方使用:在test_helper.rb

class ActiveSupport::TestCase
  def assert_raises_with_message(exception, msg, &block)
    block.call
  rescue exception => e
    assert_match msg, e.message
  else
    raise "Expected to raise #{exception} w/ message #{msg}, none raised"
  end
end

并在您的测试,如使用它:

assert_raises_with_message RuntimeError, 'Foo' do
  code_that_raises_RuntimeError_with_Foo_message
end


Answer 4:

要添加一些更近期的发展,已经有一些讨论关于增加assert_raises_with_message在过去MINITEST没有多少运气。

目前,有前途的拉动请求被合并的等待。 如果当它被合并了,我们就可以使用assert_raises_with_message不必定义它自己。

在此期间,有一个名为这个方便的小宝石MINITEST奖金,断言它精确地定义该方法,与其他几个一起,这样就可以用它的开箱。 查看文档以获取更多信息。



文章来源: What is the expected syntax for checking exception messages in MiniTest's assert_raises/must_raise?