assert_raises
在 MiniTest 的/中检查异常消息的预期语法是什么must_raise
?
我正在尝试做出类似以下的断言,"Foo"
预期的错误消息在哪里:
proc { bar.do_it }.must_raise RuntimeError.new("Foo")
您可以使用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
断言异常:
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)
Minitest 还没有为您提供检查实际异常消息的方法。但是您可以添加一个辅助方法来执行此操作并扩展ActiveSupport::TestCase
类以在您的 Rails 测试套件中的任何地方使用,例如: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
为了添加一些最近的发展,过去有一些关于添加assert_raises_with_message
到 minitest 的讨论,但运气不佳。
目前,有一个有希望的拉取请求等待合并。如果并且当它被合并时,我们将能够使用assert_raises_with_message
而无需自己定义它。
同时,有一个名为minitest-bonus-assertions 的方便的小 gem ,它准确地定义了该方法以及其他一些方法,以便您可以开箱即用地使用它。有关更多信息,请参阅文档。