How do I test for an exception in minitest?

I'm using Rails 5 with minitest. How do I properly catch an exception being raised from invoking a controller method? I thought


was the key. However, I have this method

  def show
    @line = Line.find(params[:id])

and although I thought I'm capturing a REcordNotFoundError but writing

  # 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)

and then running it results in a

# Running:


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>'

error. What's the right way to catch the error in my test?

1 answer

  • answered 2018-01-12 01:25 Taryn East

    assert_raises expects a block - you've just called the code.

    Try something like:

    assert_raises ActiveRecord::RecordNotFound do
      get line_path(invalid_line_id)