Rails ActiveSupport: How to assert that an error is raised?

强颜欢笑 提交于 2019-11-29 00:53:19
Matt Briggs

So unit testing isn't really in activesupport. Ruby comes with a typical xunit framework in the standard libs (Test::Unit in ruby 1.8.x, MiniTest in ruby 1.9), and the stuff in activesupport just adds some stuff to it.

If you are using Test::Unit/MiniTest

assert_raise(Exception) { whatever.merge }

if you are using rspec (unfortunately poorly documented, but way more popular)

lambda { whatever.merge }.should raise_error

If you want to check the raised Exception:

exception = assert_raises(Exception) { whatever.merge }
assert_equal( "message", exception.message )

To ensure that no exception is raised (or is successfully handled) do inside your test case:

assert_nothing_raised RuntimeError do
  whatever.merge
end

To check that error is raised do inside your test case:

assert_raise RuntimeError do
  whatever.merge
end

Just a heads up, whatever.merge is the code that raises the error (or doesn't, depending on the assertion type).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!