我使用Rails 5和minitest。如何正确捕获从调用控制器方法引发的异常?我想
assert_raises
是关键。但是,我有这个方法
def show
@line = Line.find(params[:id])
end
虽然我认为我正在捕获REcordNotFoundError但是正在编写
# Simple test to verify we get the show page when we
# invoke the page with a valid ID
test "get show page with invalid line id" do
invalid_line_id = -1
assert_raises ActiveRecord::RecordNotFound get line_path(invalid_line_id)
end
然后运行它会产生
# Running:
.E
Error:
LinesControllerTest#test_get_show_page_with_invalid_line_id:
ActiveRecord::RecordNotFound: Couldn't find Line with 'onestop_id'=-1
app/controllers/lines_controller.rb:7:in `show'
test/controllers/lines_controller_test.rb:31:in `block in <class:LinesControllerTest>'
错误。在测试中捕获错误的正确方法是什么?
答案 0 :(得分:1)
assert_raises
需要一个块 - 您刚刚调用了代码。
尝试类似:
assert_raises ActiveRecord::RecordNotFound do
get line_path(invalid_line_id)
end