Search⌘ K

Testing Server-rendered HTML Applications

Explore testing techniques for server-rendered HTML endpoints in Phoenix applications. Learn to write controller tests that verify the rendering of HTML forms and user creation workflows, using Phoenix helpers and assertions with ExUnit. This lesson prepares you to ensure your server-rendered interfaces work correctly and maintain high test coverage.

We'll cover the following...

Testing server-rendered HTML endpoints is very similar to testing JSON endpoints, but the response is an HTML document instead of JSON.

Controller

We’ll write tests for the user controller that handles the server-rendered HTML endpoints. Let’s start by looking at the controller code that we’ll be testing:

Elixir
#file path -> lib/not_skull_web/controllers/user_controller.ex
#add this code at the indicated place mentioned in comments of lib/not_skull_web/
#controllers/user_controller.ex in the playground widget
defmodule NotSkullWeb.UserController do
use NotSkullWeb, :controller
alias NotSkull.Accounts
alias NotSkull.Accounts.User
alias NotSkull.ExternalServices.Email
def new(conn, _params) do
user = User.create_changeset(%{})
render(conn, "new.html", changeset: user)
end
def create(conn, %{"user" => user_params}) do
case Accounts.create_user(user_params) do
{:ok, user} ->
Email.send_welcome(user)
conn
|> put_session(:user_id, user.id)
|> put_flash(:info, "Your account was created successfully!")
|> redirect(to: Routes.user_path(conn, :show, user))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
end

This code is a controller that, under the hood, calls to the same context module as the JSON controller we’ve already tested. Our testing will focus on the two endpoints that call the new and create controller ...

...