# Running doctests against the database

Doctests are straightforward until an example calls `Repo`. A plain ExUnit case doesn't check out an Ecto sandbox connection, so run database-backed doctests through your application's `DataCase`:

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

  doctest MyApp.Accounts
end
```

The doctest still needs to create the data it uses:

```elixir
@doc """
Finds a user by email.

    iex> {:ok, user} =
    ...>   register_user(%{email: "john@example.com"})

    iex> get_user_by_email("john@example.com").id == user.id
    true

"""
def get_user_by_email(email) do
  Repo.get_by(User, email: email)
end
```

`doctest` generates a regular ExUnit test from the example. `DataCase` gives that test its own sandbox connection, and the example inserts the user before trying to find it. The transaction is rolled back afterward, so the user doesn't leak into another test.

Mind you, this works well for small examples. Once a doctest needs several fixtures and half the application running, move it to a normal test.

Related: https://hexdocs.pm/ex_unit/ExUnit.DocTest.html


---

Created by: almirsarajcic
Date: September 21, 2026
URL: https://elixirdrops.net/d/xemXGQJq
