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)
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)
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)
| 归档时间: |
|
| 查看次数: |
31849 次 |
| 最近记录: |