Search⌘ K
AI Features

Testing the Happy Path

Explore how to write a happy path test for a Phoenix controller using ExUnit. Understand structuring tests that verify HTTP 200 responses, JSON output, and database side effects to ensure correct application behavior.

Defining the happy path test

The test is structured very similarly to the error test from the previous lesson. The common elements are these:

  • It accepts a context with a Plug.Conn that contains a valid JWT.

  • It calls the endpoint using put/3, a helper from the Phoenix library.

  • It uses json_response/2 to assert on the HTTP response code and to deserialize the JSON response.

  • It makes assertions on the return value.

  • It makes assertions on the side effects.

Let’s add the following test inside the describe block PUT /api/users/:id.

Elixir
#file path -> test/not_skull_web/controllers/user_controller_test.exs
#add this code at the indicated place mentioned in comments of test/not_skull_web/controllers/
#user_controller_test.exs in the playground widget
test "success: updates db returns record with good params", %{
conn_with_token: conn_with_token,
user: existing_user
} do
new_name = "#{existing_user.name}-updated"
conn =
put(conn_with_token, "/api/users/#{existing_user.id}", %{
name: new_name
})
assert parsed_return = json_response(conn, 200)
user_from_db = Repo.get(User, existing_user.id)
assert_values_for(
expected: %{existing_user | name: new_name},
actual: user_from_db,
fields: fields_for(User) -- [:updated_at]
)
assert DateTime.to_unix(user_from_db.updated_at, :microsecond) >
DateTime.to_unix(existing_user.updated_at, :microsecond)
# checking that the updated record is what is returned from endpoint
assert_values_for(
expected: user_from_db,
actual: {parsed_return, :string_keys},
fields: fields_for(User),
opts: [convert_dates: true]
)
end
...