Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Testing and Deployment

Testing Controllers and Contexts

Test a Phoenix app with ExUnit: DataCase for contexts, ConnCase for controllers, fixtures, the Ecto SQL sandbox, authenticated tests, JSON APIs and mocking with Mox.

Phoenix treats tests as part of the framework. Every generated project has a test/ folder, a database sandbox, two helper modules (DataCase and ConnCase) and a test for every generated feature. Because Elixir data is immutable and the request is just a function of a struct, Phoenix tests are fast, and most of them can run at the same time.

This lesson covers the two main kinds of tests in a Phoenix app: context tests (business logic and the database) and controller tests (an HTTP request in, a response out). LiveView has its own tools, covered in Testing LiveView. The real ExUnit code is read-only on this site; the runnable stand-ins show the mechanics in JavaScript. If ExUnit is new, read Testing with ExUnit first.

What mix test does

Terminal
mix test                       # everything
mix test test/my_app/blog_test.exs         # one file
mix test test/my_app/blog_test.exs:25      # the test at line 25
mix test --failed              # only tests that failed last time
mix test --stale               # only tests affected by changed files

mix test runs the test alias from mix.exs, which creates the database, runs migrations and then your tests, using config/test.exs. That config points to a separate database (my_app_test) so tests never touch development data.

Context tests with DataCase

A context test calls plain Elixir functions and checks results. DataCase sets up the Ecto SQL sandbox: each test runs inside a database transaction that is rolled back at the end, so tests cannot see each other's data and need no cleanup.

ELIXIR
defmodule MyApp.BlogTest do
  use MyApp.DataCase, async: true

  alias MyApp.Blog
  import MyApp.BlogFixtures

  describe "create_post/1" do
    test "with valid data creates a post" do
      attrs = %{title: "Hello Phoenix", body: "First post"}

      assert {:ok, post} = Blog.create_post(attrs)
      assert post.title == "Hello Phoenix"
    end

    test "with a blank title returns an error changeset" do
      assert {:error, changeset} = Blog.create_post(%{title: "", body: "x"})
      assert "can't be blank" in errors_on(changeset).title
    end
  end

  describe "list_posts/0" do
    test "returns all posts, newest first" do
      older = post_fixture(title: "Older")
      newer = post_fixture(title: "Newer")

      assert Blog.list_posts() == [newer, older]
    end
  end
end

Things to notice:

  • async: true lets this module run in parallel with others. The sandbox makes that safe, because every test has its own transaction. (Do not use it for tests that change global state, such as application env or named processes.)
  • Fixtures are plain functions in test/support/fixtures/ that insert valid records, taking overrides for the fields you care about. A good fixture makes the important value obvious in the test (title: "Older") and hides the rest.
  • errors_on/1 (generated in DataCase) turns a changeset into %{title: ["can't be blank"]}.
  • Assert the shape you care about with pattern matching: assert {:ok, post} = ... both asserts and binds.
Node.js How the SQL sandbox isolates tests (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Controller tests with ConnCase

ConnCase gives you a conn struct, a fake HTTP connection, and the helpers to send a request through the whole endpoint (router, plugs, controller, view) without opening a network port.

ELIXIR
defmodule MyAppWeb.PostControllerTest do
  use MyAppWeb.ConnCase, async: true
  import MyApp.BlogFixtures

  describe "GET /posts" do
    test "lists posts", %{conn: conn} do
      post = post_fixture(title: "Visible title")

      conn = get(conn, ~p"/posts")

      assert html_response(conn, 200) =~ "Visible title"
    end
  end

  describe "POST /posts" do
    test "redirects to the new post when data is valid", %{conn: conn} do
      conn = post(conn, ~p"/posts", post: %{title: "New", body: "Body"})

      assert %{id: id} = redirected_params(conn)
      assert redirected_to(conn) == ~p"/posts/#{id}"
    end

    test "re-renders the form when data is invalid", %{conn: conn} do
      conn = post(conn, ~p"/posts", post: %{title: ""})

      assert html_response(conn, 200) =~ "can't be blank"
    end
  end
end

The verbs get/2, post/3, put/3, delete/2 build and send a request. Assert with html_response/2, json_response/2, redirected_to/1, response/2 or by reading conn.status, conn.assigns and get_resp_header/2. The ~p sigil gives verified routes: a typo in a path is a compile warning, not a failing test.

Authenticated requests

Projects generated with mix phx.gen.auth include a setup function that creates a user and logs them in by putting a valid session token in the test conn:

ELIXIR
describe "GET /invoices" do
  setup :register_and_log_in_user

  test "shows only my invoices", %{conn: conn, user: user, scope: scope} do
    mine = invoice_fixture(scope, title: "Mine")
    other = invoice_fixture(user_scope_fixture(), title: "Not mine")

    html = conn |> get(~p"/invoices") |> html_response(200)

    assert html =~ mine.title
    refute html =~ other.title
  end

  test "another user's invoice is a 404", %{conn: conn} do
    other = invoice_fixture(user_scope_fixture())
    assert_error_sent 404, fn -> get(conn, ~p"/invoices/#{other}") end
  end
end

The second test is the most valuable one in the file: it proves the authorization rules work. Write a "user B cannot touch user A's data" test for every resource.

JSON APIs

For an API pipeline set the accept header and assert JSON:

ELIXIR
test "creates a post", %{conn: conn} do
  conn =
    conn
    |> put_req_header("accept", "application/json")
    |> post(~p"/api/posts", post: %{title: "API post", body: "x"})

  assert %{"id" => id, "title" => "API post"} = json_response(conn, 201)["data"]
  assert get_resp_header(conn, "location") == [~p"/api/posts/#{id}"]
end

A model of a connection test

A controller test is essentially: build a request, run it through the pipeline, assert on the response. The stand-in implements that in miniature, with a router, a pipeline plug that blocks anonymous users, and the assertion helpers.

Node.js A request through router, plugs and controller (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Mocking external services

Never call a real payment provider or email service in tests. The idiomatic Elixir way is to define a behaviour for the boundary, configure the real module in config.exs, and use a mock in config/test.exs. The Mox library generates the mock from the behaviour:

ELIXIR
# lib/my_app/payments.ex
defmodule MyApp.Payments do
  @callback charge(integer(), String.t()) :: {:ok, String.t()} | {:error, term()}
end

# test/support/mocks.ex
Mox.defmock(MyApp.PaymentsMock, for: MyApp.Payments)

# config/test.exs
config :my_app, :payments, MyApp.PaymentsMock

# in a test
import Mox
setup :verify_on_exit!

test "failed charge returns an error" do
  expect(MyApp.PaymentsMock, :charge, fn 1000, "tok_123" -> {:error, :card_declined} end)
  assert {:error, :card_declined} = Billing.checkout(1000, "tok_123")
end

This ties directly to protocols and behaviours. Emails use the same idea: Swoosh's Swoosh.Adapters.Test collects mail so you can assert with assert_email_sent/1.

Habits of good Phoenix tests

  • Test the context thoroughly and the controller lightly: controllers should be thin, so one success test and one failure test per action is enough.
  • Name tests as sentences: test "with a blank title returns an error changeset".
  • Prefer fixtures over factories of random data so failures are reproducible; if you use random values, print the seed (ExUnit already does).
  • Run mix test in CI with --warnings-as-errors to catch compile warnings early.
  • Keep tests independent of order; if one needs another to pass, they are really one test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Ecto SQL sandbox do for tests?

    Rolled-back transactions mean no leftover rows and make async: true tests safe.
  2. 2. Which helper do you use to assert that a controller action redirected?

    redirected_to(conn) returns the Location header of a redirect response and checks the status is 3xx.
  3. 3. What is the most valuable authorization test?

    It proves that scoping works, which protects against the most common data leak.
  4. 4. How do you avoid calling a real payment API in tests?

    Behaviours define the boundary, and Mox verifies that expectations were met.

Summary

  • mix test runs ExUnit against a separate test database; use file and line filters while working.
  • DataCase tests contexts inside a rolled-back sandbox transaction; async: true is safe.
  • ConnCase sends requests through the full endpoint; assert with html_response, json_response and redirected_to.
  • Use register_and_log_in_user for signed-in tests and always test that users cannot touch each other's data.
  • Mock boundaries with behaviours and Mox.

Next: Testing LiveView