Testing Phoenix Applications with ExUnit: Controllers, LiveView, and Channels

Testing Phoenix Applications with ExUnit: Controllers, LiveView, and Channels

Phoenix gives you a full testing toolkit out of the box. mix phx.new scaffolds a test/ directory with helpers, a pre-configured Ecto sandbox, and imports for every layer of the stack. Most teams don't use half of what's there. This guide covers all of it.

Project Structure

When you generate a Phoenix app, you get:

test/
  support/
    conn_case.ex        # ConnCase — base for controller/channel tests
    channel_case.ex     # ChannelCase — base for channel tests
    data_case.ex        # DataCase — base for context/schema tests
    factory.ex          # (add this yourself for ex_machina)
  my_app_web/
    controllers/
    live/
    channels/
  my_app/
    accounts_test.exs   # Context tests

Each *_case.ex file uses ExUnit.CaseTemplate to share setup logic across test modules. Understanding what each one does saves you from repeating boilerplate.

ConnCase: The Foundation for HTTP Tests

ConnCase sets up a %Plug.Conn{} and imports Phoenix test helpers:

# test/support/conn_case.ex (generated)
defmodule MyAppWeb.ConnCase do
  use ExUnit.CaseTemplate

  using do
    quote do
      import Plug.Conn
      import Phoenix.ConnTest
      import MyAppWeb.Router.Helpers

      @endpoint MyAppWeb.Endpoint
    end
  end

  setup tags do
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)

    unless tags[:async] do
      Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()})
    end

    {:ok, conn: Phoenix.ConnTest.build_conn()}
  end
end

The build_conn() call creates a fresh connection for each test. The Ecto sandbox checkout ensures each test runs in a transaction that rolls back at the end — no leftover data between tests.

Testing Controllers

GET requests

defmodule MyAppWeb.PageControllerTest do
  use MyAppWeb.ConnCase

  test "GET / returns 200", %{conn: conn} do
    conn = get(conn, ~p"/")
    assert html_response(conn, 200) =~ "Welcome"
  end

  test "GET /about renders about page", %{conn: conn} do
    conn = get(conn, ~p"/about")
    assert html_response(conn, 200) =~ "<h1>About</h1>"
  end
end

The ~p"/path" sigil is Phoenix's verified routes — compile-time checking that the route exists. html_response(conn, 200) asserts the status code and returns the response body as a string, which you can match against with =~.

POST, PUT, DELETE

defmodule MyAppWeb.UserControllerTest do
  use MyAppWeb.ConnCase

  describe "POST /users" do
    test "creates user with valid params", %{conn: conn} do
      params = %{user: %{email: "test@example.com", password: "securepass123"}}

      conn = post(conn, ~p"/users", params)

      assert redirected_to(conn) == ~p"/users/1"
      assert get_flash(conn, :info) =~ "User created"
    end

    test "re-renders form with invalid params", %{conn: conn} do
      conn = post(conn, ~p"/users", %{user: %{email: "not-an-email"}})

      assert html_response(conn, 422) =~ "is invalid"
    end
  end

  describe "DELETE /users/:id" do
    test "deletes user and redirects", %{conn: conn} do
      user = insert(:user)

      conn = delete(conn, ~p"/users/#{user.id}")

      assert redirected_to(conn) == ~p"/users"
      assert_raise Ecto.NoResultsError, fn -> MyApp.Accounts.get_user!(user.id) end
    end
  end
end

redirected_to/1 returns the redirect location. get_flash/2 reads flash messages from the session.

Authentication

Testing authenticated routes requires setting up session or token state. The cleanest approach is a helper that logs in a user on the conn:

# test/support/conn_case.ex — add to the using block
def log_in_user(conn, user) do
  token = MyApp.Accounts.generate_user_session_token(user)

  conn
  |> Phoenix.ConnTest.init_test_session(%{})
  |> Plug.Conn.put_session(:user_token, token)
end

Use it in tests:

describe "authenticated routes" do
  setup %{conn: conn} do
    user = insert(:user)
    conn = log_in_user(conn, user)
    {:ok, conn: conn, user: user}
  end

  test "GET /dashboard returns 200", %{conn: conn} do
    conn = get(conn, ~p"/dashboard")
    assert html_response(conn, 200) =~ "Dashboard"
  end

  test "GET /dashboard without auth redirects to login", %{conn: conn} do
    # Use a fresh conn without authentication
    conn = build_conn()
    conn = get(conn, ~p"/dashboard")
    assert redirected_to(conn) == ~p"/users/log_in"
  end
end

Testing JSON APIs

JSON APIs need content-type headers and JSON parsing:

defmodule MyAppWeb.API.UserControllerTest do
  use MyAppWeb.ConnCase

  setup %{conn: conn} do
    conn =
      conn
      |> put_req_header("accept", "application/json")
      |> put_req_header("content-type", "application/json")

    {:ok, conn: conn}
  end

  test "GET /api/users returns user list", %{conn: conn} do
    insert(:user, email: "alice@example.com")
    insert(:user, email: "bob@example.com")

    conn = get(conn, ~p"/api/users")

    assert %{"data" => users} = json_response(conn, 200)
    assert length(users) == 2
    emails = Enum.map(users, & &1["email"])
    assert "alice@example.com" in emails
  end

  test "POST /api/users creates user", %{conn: conn} do
    conn = post(conn, ~p"/api/users", %{email: "new@example.com", password: "pass123"})

    assert %{"data" => %{"id" => id, "email" => "new@example.com"}} = json_response(conn, 201)
    assert is_integer(id)
  end

  test "POST /api/users returns validation errors", %{conn: conn} do
    conn = post(conn, ~p"/api/users", %{email: "bad"})

    assert %{"errors" => errors} = json_response(conn, 422)
    assert errors["email"] == ["has invalid format"]
  end
end

json_response(conn, 200) asserts the status and decodes the JSON body. Pattern match directly on the result — it's cleaner than pulling keys manually.

API Authentication with Bearer Tokens

setup %{conn: conn} do
  user = insert(:user)
  token = MyApp.Accounts.create_api_token(user)

  conn =
    conn
    |> put_req_header("authorization", "Bearer #{token}")
    |> put_req_header("accept", "application/json")

  {:ok, conn: conn, user: user}
end

Testing Phoenix LiveView

LiveView tests use Phoenix.LiveViewTest. The key functions are live/2, render_click/2, render_submit/3, and assert_patch/2.

defmodule MyAppWeb.UserListLiveTest do
  use MyAppWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  test "renders user list", %{conn: conn} do
    insert(:user, name: "Alice")
    insert(:user, name: "Bob")

    {:ok, view, html} = live(conn, ~p"/users")

    assert html =~ "Alice"
    assert html =~ "Bob"
  end

  test "filters users by search term", %{conn: conn} do
    insert(:user, name: "Alice")
    insert(:user, name: "Bob")

    {:ok, view, _html} = live(conn, ~p"/users")

    html = render_change(view, "search", %{query: "Alice"})

    assert html =~ "Alice"
    refute html =~ "Bob"
  end
end

render_click and render_submit

test "deletes user on click", %{conn: conn} do
  user = insert(:user, name: "Alice")

  {:ok, view, _html} = live(conn, ~p"/users")

  assert view |> element("[data-user-id='#{user.id}'] [data-action='delete']") |> render_click()

  refute render(view) =~ "Alice"
end

test "creates user via form submit", %{conn: conn} do
  {:ok, view, _html} = live(conn, ~p"/users/new")

  html =
    view
    |> form("#user-form", user: %{name: "Charlie", email: "charlie@example.com"})
    |> render_submit()

  assert_patch(view, ~p"/users")
  assert render(view) =~ "Charlie"
end

element/2 scopes interactions to a specific DOM element using a CSS selector. form/3 finds a form and fills in fields. This avoids hardcoding event names and keeps tests tied to the actual UI structure.

assert_patch and assert_redirect

test "navigates to edit page", %{conn: conn} do
  user = insert(:user)

  {:ok, view, _html} = live(conn, ~p"/users")

  view |> element("[data-action='edit'][data-id='#{user.id}']") |> render_click()

  assert_patch(view, ~p"/users/#{user.id}/edit")
end

test "redirects to login when not authenticated", %{conn: conn} do
  {:error, {:redirect, %{to: path}}} = live(conn, ~p"/dashboard")
  assert path == "/users/log_in"
end

assert_patch/2 checks that the LiveView patched (pushState navigation without a full page reload). assert_redirect/2 checks for full redirects.

Testing LiveView Components

defmodule MyAppWeb.Components.UserCardTest do
  use MyAppWeb.ConnCase, async: true
  import Phoenix.LiveViewTest

  test "renders user name and email" do
    assigns = %{user: %{name: "Alice", email: "alice@example.com"}}

    html = render_component(MyAppWeb.Components.UserCard, assigns)

    assert html =~ "Alice"
    assert html =~ "alice@example.com"
  end
end

render_component/2 renders a stateless function component or stateful LiveComponent directly, without needing a full LiveView mount.

Testing Phoenix Channels

Channel tests require a ChannelCase:

defmodule MyAppWeb.RoomChannelTest do
  use MyAppWeb.ChannelCase

  setup do
    {:ok, _, socket} =
      MyAppWeb.UserSocket
      |> socket("user_id", %{user_id: 42})
      |> subscribe_and_join(MyAppWeb.RoomChannel, "room:lobby")

    {:ok, socket: socket}
  end

  test "joins room successfully", %{socket: socket} do
    assert socket.topic == "room:lobby"
  end

  test "broadcasts message to room", %{socket: socket} do
    push(socket, "new_message", %{body: "hello"})

    assert_broadcast "new_message", %{body: "hello"}
  end

  test "sends reply on ping", %{socket: socket} do
    ref = push(socket, "ping", %{})
    assert_reply ref, :ok, %{message: "pong"}
  end

  test "broadcasts presence update on join", %{socket: _socket} do
    assert_broadcast "presence_state", _
  end
end

Key helpers:

  • socket/3 — creates a test socket with the given ID and assigns
  • subscribe_and_join/3 — joins a channel topic
  • push/3 — sends a message from client to server
  • assert_broadcast/2 — checks that a message was broadcast to the topic
  • assert_reply/3 — checks the reply sent back to the pushing client
  • assert_push/2 — checks that the server pushed a message to the client

Ecto Sandbox for Database Isolation

The Ecto SQL sandbox wraps each test in a database transaction that rolls back at the end. No test data persists between tests. This is what makes database tests fast and deterministic.

Checkout modes

Checked out (default for sync tests):

Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)

The test process owns the transaction. Only that process can use the connection.

Shared mode (for async tests that spawn processes):

Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()})

Allows processes spawned by the test to use the same connection. Required when testing code that uses Task, GenServer, or LiveView (which runs in its own process).

ConnCase and DataCase handle this automatically based on the async tag.

Manual sandbox in integration tests

When testing background jobs or GenServers that access the DB, allow the process to use the sandbox:

test "background job processes record" do
  record = insert(:record, status: :pending)

  pid = start_supervised!(MyApp.BackgroundJob)
  Ecto.Adapters.SQL.Sandbox.allow(MyApp.Repo, self(), pid)

  MyApp.BackgroundJob.process(pid, record.id)

  assert MyApp.Repo.get!(Record, record.id).status == :completed
end

allow/3 grants a specific process access to the current test's sandbox connection.

Factory Pattern with ex_machina

ex_machina gives you composable factories for test data. Add it to deps:

{:ex_machina, "~> 2.8", only: :test}

Define your factory:

# test/support/factory.ex
defmodule MyApp.Factory do
  use ExMachina.Ecto, repo: MyApp.Repo

  def user_factory do
    %MyApp.Accounts.User{
      name: sequence(:name, &"User #{&1}"),
      email: sequence(:email, &"user#{&1}@example.com"),
      role: :member,
      inserted_at: ~N[2024-01-01 00:00:00],
      updated_at: ~N[2024-01-01 00:00:00]
    }
  end

  def admin_user_factory do
    struct!(user_factory(), role: :admin)
  end

  def post_factory do
    %MyApp.Content.Post{
      title: sequence(:title, &"Post #{&1}"),
      body: "Default post body",
      status: :draft,
      author: build(:user)
    }
  end
end

Import in your case templates:

# In ConnCase, DataCase using block:
import MyApp.Factory

Use in tests:

# Build (no DB insert)
user = build(:user)
user = build(:user, name: "Alice", role: :admin)

# Insert (DB insert)
user = insert(:user)
user = insert(:user, email: "custom@example.com")

# Insert with association
post = insert(:post, author: insert(:user, name: "Alice"))

# Use a named factory
admin = insert(:admin_user)

# Insert list
users = insert_list(3, :user)

# Build list (no DB)
attrs_list = params_for(:user)

sequence/2 generates unique values per call — essential for fields with uniqueness constraints like email.

Traits for complex variations

def user_factory do
  %MyApp.Accounts.User{
    name: "Default User",
    email: sequence(:email, &"user#{&1}@example.com"),
    role: :member,
    confirmed_at: nil
  }
end

def confirmed_user_factory do
  struct!(user_factory(), confirmed_at: ~N[2024-01-01 00:00:00])
end

def suspended_user_factory do
  struct!(user_factory(), role: :suspended)
end

Prefer named factories over merging too many attributes at call sites — it keeps tests readable when you're scanning them three months later.

DataCase for Context Tests

Context modules (the business logic layer in Phoenix) don't go through HTTP. Test them with DataCase:

defmodule MyApp.AccountsTest do
  use MyApp.DataCase, async: true

  alias MyApp.Accounts

  describe "create_user/1" do
    test "succeeds with valid attrs" do
      attrs = %{email: "test@example.com", password: "securepass123"}

      assert {:ok, user} = Accounts.create_user(attrs)
      assert user.email == "test@example.com"
      assert user.id != nil
    end

    test "returns error changeset with duplicate email" do
      insert(:user, email: "taken@example.com")

      assert {:error, changeset} = Accounts.create_user(%{email: "taken@example.com", password: "pass"})
      assert "has already been taken" in errors_on(changeset).email
    end
  end
end

errors_on/1 is a helper from DataCase that extracts changeset errors as a map of field => [messages]. Much cleaner than digging into changeset.errors manually.

Putting It Together: A Test Strategy

For a Phoenix app, the testing layers look like this:

Layer Test type Use
Schemas DataCase Changeset validation, virtual fields
Contexts DataCase Business logic, DB queries
Controllers ConnCase HTTP request/response, redirects
JSON API ConnCase Status codes, response shape
LiveView ConnCase User interactions, DOM assertions
Channels ChannelCase Real-time message handling

Keep context tests fast and isolated. Push complex setup into factories. Run controller tests with async: false only when you have to — most Phoenix controller tests work fine with async: true once the Ecto sandbox is in shared mode.

For the full picture — including what happens when users actually flow through your Phoenix app end-to-end in a browser — HelpMeTest lets you write those scenarios in plain English and run them continuously against your deployed environment, catching regressions that unit tests can't see.

Read more

Start now free