Phoenix: assert_error_sent is not passing tests with 404 given a 404

Created on 5 Mar 2016  路  6Comments  路  Source: phoenixframework/phoenix

Apologies if the offending code/macro/function does not belong to this repo. This happened inside my phoenix project so I figured it belonged here.

Environment

  • Elixir version (elixir -v): Elixir 1.2.2
  • Phoenix version (mix deps): phoenix 1.1.4
  • NodeJS version (node -v): v5.5.0
  • NPM version (npm -v): 3.5.3
  • Operating system: {:unix, :darwin} - OSX Yosemite 10.10.5 (14F27)

    Expected behavior

In a newly generated test the following test should pass without incident:

test "does not show resource and instead throw error when id is nonexistent", %{conn: conn} do
  assert_error_sent 404, fn ->
    get conn, user_path(conn, :show, -1)
  end
end

Actual behavior

  1) test does not show resource and instead throw error when id is nonexistent (MyApp.UserControllerTest)
     test/controllers/user_controller_test.exs:45
     expected error to be sent as 404 status, but response sent 404 without error
     stacktrace:
       (phoenix) lib/phoenix/test/conn_test.ex:531: Phoenix.ConnTest.assert_error_sent/2
       test/controllers/user_controller_test.exs:46

Most helpful comment

@flomop assert_error_sent is for asserting an exception was caught and translated to a response. Your put_status(403) code is just fine, but it doesn't raise an error. A test case for that would be:

assert html_response(conn, 403) =~ "Error explanation"

All 6 comments

for the time being this seems to work well enough and is passing:

  test "does not show resource and instead throw error when id is nonexistent", %{conn: conn} do
    conn = get conn, user_path(conn, :show, -1)
    assert conn.status == 404
  end

assert_error_sent should only be used if the connection is raising an exception. If it's just normally returning a 404 you should do a normal assertion. Notice the end "without error" in the error message "expected error to be sent as 404 status, but response sent 404 without error" it means that 404 was returned but no error was raised.

Thanks for the explanation, ericmj.

@ericmj, how can I raise 403 exception so it will be recognized by assert_error_sent?

I tried this:
put_status( 403) |> render( ErrorView, "403.html", error: "Error explanation.")

and this:
send_resp( 403, "Error msg.")

But have no luck in both cases.

@flomop assert_error_sent is for asserting an exception was caught and translated to a response. Your put_status(403) code is just fine, but it doesn't raise an error. A test case for that would be:

assert html_response(conn, 403) =~ "Error explanation"

Thanks for explanation, @chrismccord ! So how someone would raise and translate exception to response? Or it's convenient to just use put_status( :forbidden) |> render( ErrorView, "403.html", error: "...") form to proceed with 403 and 401 errors?

Was this page helpful?
0 / 5 - 0 ratings