Phoenix - testing JSON Api

I am trying to write some tests for a JSON Api. If something in the action raises an error, I would like a JSON error to be returned to my test.

Action

def get(conn, params) do
   1=2
end

My test

test "Get always returns 500 - internal server error", %{conn: conn} do
   conn = get(conn, Routes.my_path(conn, :get_it)
   assert json_response(conn, 500)["errors"] != %{}
end

test raises an error: ‘no mach of right hand…’ Instead of it raising an error, I would like to capture a 500 error similar to what the client will get.

Seems that you’re looking for assert_error_sent.

3 Likes

Yes, that was it. Coupled with my lack of understand of how to return a non-200 result code back to client. I think i have this figured out now.

conn
|> put_status(:not_found)
|> json(%{"Errors" => "Not found"})

Will allow the client/test to receive a normal HTTP response. If an error is raised, like a match error, that will automatically return a 500 result code and the test has to use the assert_error_sent