Ecto.Adapters.SQL.begin_test_transaction/2

Parsed documentation:
View on GitHub
Starts a transaction for test.

This function work by starting a transaction and storing the connection
back in the pool with an open transaction. On every test, we restart
the test transaction rolling back to the appropriate savepoint.

**IMPORTANT:** Test transactions only work if the connection pool has
size of 1 and does not support any overflow.

## Example

The first step is to configure your database pool to have size of
1 and no max overflow. You set those options in your `config/config.exs`:

    config :my_app, Repo,
      size: 1,
      max_overflow: 0

Since you don't want those options in your production database, we
typically recommend to create a `config/test.exs` and add the
following to the bottom of your `config/config.exs` file:

    import_config "config/#{Mix.env}.exs"

Now with the test database properly configured, you can write
transactional tests:

    # At the end of your test_helper.exs
    # From now, all tests happen inside a transaction
    Ecto.Adapters.SQL.begin_test_transaction(TestRepo)

    defmodule PostTest do
      # Tests that use the shared repository cannot be async
      use ExUnit.Case

      setup do
        # Go back to a clean slate at the beginning of every test
        Ecto.Adapters.SQL.restart_test_transaction(TestRepo)
        :ok
      end

      test "create comment" do
        assert %Post{} = TestRepo.insert(%Post{})
      end
    end

In some cases, you may want to start the test transaction only
for specific tests and then roll it back. You can do it as:

    defmodule PostTest do
      # Tests that use the shared repository cannot be async
      use ExUnit.Case

      setup_all do
        # Wrap this case in a transaction
        Ecto.Adapters.SQL.begin_test_transaction(TestRepo)

        # Roll it back once we are done
        on_exit fn ->
          Ecto.Adapters.SQL.rollback_test_transaction(TestRepo)
        end

        :ok
      end

      setup do
        # Go back to a clean slate at the beginning of every test
        Ecto.Adapters.SQL.restart_test_transaction(TestRepo)
        :ok
      end

      test "create comment" do
        assert %Post{} = TestRepo.insert(%Post{})
      end
    end
Suggestions:
Please help! Open an issue on GitHub if this assessment is incorrect.