We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Running doctests against the database
almirsarajcic
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:
defmodule MyApp.AccountsTest do
use MyApp.DataCase, async: true
doctest MyApp.Accounts
end
The doctest still needs to create the data it uses:
@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.
copied to clipboard