如何在minitest中测试异常?

时间:2018-01-11 19:58:46

标签: unit-testing exception controller ruby-on-rails-5 minitest

我使用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>'

错误。在测试中捕获错误的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

assert_raises需要一个块 - 您刚刚调用了代码。

尝试类似:

assert_raises ActiveRecord::RecordNotFound do
  get line_path(invalid_line_id)
end