defmodule UpiSettlement.DataCase do @moduledoc """ ExUnit case template for tests that access the database. Uses `UpiCore.Repo` with the SQL sandbox so all DB changes made in a test are rolled back at the end of that test. Each test gets a clean slate. Usage: use UpiSettlement.DataCase """ use ExUnit.CaseTemplate using do quote do alias UpiCore.Repo import Ecto import Ecto.Changeset import Ecto.Query import UpiSettlement.DataCase import UpiSettlement.Fixtures end end setup do {:ok, _} = Application.ensure_all_started(:upi_core) setup_sandbox(%{async: false}) :ok end def setup_sandbox(tags) do pid = Ecto.Adapters.SQL.Sandbox.start_owner!(UpiCore.Repo, shared: not tags[:async]) on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) end @doc """ Transforms changeset errors into a map of messages. assert {:error, changeset} = ... assert "is invalid" in errors_on(changeset).status """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} -> Regex.replace(~r"%{(\w+)}", msg, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end) end) end end