Elixir: Using CaseTemplate for DB Setup and Teardown

After spending some time spinning my wheels on figuring out how to clean up after each test run, I discovered some functions defined in the Ecto.Adapters.SQL module. Including this template in your test files that integrate with the database will give you a clean slate for each test run. Enjoy!

defmodule DBTransactions do
  use ExUnit.CaseTemplate

  setup_all do
    Ecto.Adapters.SQL.begin_test_transaction(Repo)

    on_exit fn ->
      Ecto.Adapters.SQL.rollback_test_transaction(Repo)
    end
  end

  setup do
    Ecto.Adapters.SQL.restart_test_transaction(Repo, [])
  end
end

# Use it in your test module
defmodule MessageTest do
  use DBTransactions
end