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

kfi*_*ick 82 ruby tdd minitest assertion

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

我正在尝试做出如下所示的断言,其中"Foo"是预期的错误消息:

proc { bar.do_it }.must_raise RuntimeError.new("Foo")
Run Code Online (Sandbox Code Playgroud)

blo*_*age 142

您可以使用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
Run Code Online (Sandbox Code Playgroud)

如果你需要在错误对象上测试一些东西,你可以从断言或期望中得到它,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

  • 更新了代码以显示如何访问错误对象. (4认同)
  • err = - > {bar.do_it} .must_raise RuntimeError语法对我不起作用,它不断引发以下异常.NoMethodError:nil的未定义方法`assert_raises':NilClass (3认同)
  • @thanikkal确保你使用的是'Minitest :: Spec`而不是'Minitest :: Test`.Spec DSL,包括期望,仅在使用`Minitest :: Spec`时可用. (2认同)

Jin*_* Li 23

断言例外:

assert_raises FooError do
  bar.do_it
end
Run Code Online (Sandbox Code Playgroud)

断言异常消息:

根据API文档,assert_raises返回匹配的异常,以便您可以检查消息,属性等.

exception = assert_raises FooError do
  bar.do_it
end
assert_equal('Foo', exception.message)
Run Code Online (Sandbox Code Playgroud)


Dev*_*per 6

Minitest不提供(还)您检查实际异常消息的方法.但是你可以添加一个辅助方法来完成它并扩展ActiveSupport::TestCase类以在rails测试套件中的任何地方使用,例如:intest_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
Run Code Online (Sandbox Code Playgroud)

并在你的测试中使用它,如:

assert_raises_with_message RuntimeError, 'Foo' do
  code_that_raises_RuntimeError_with_Foo_message
end
Run Code Online (Sandbox Code Playgroud)

  • 确实Minitest不支持检查错误消息,但是可以使用`must_raise`来实现,因为它为您提供了错误的实例,因此您可以自己检查消息. (2认同)