Surgex.DatabaseCleaner (Surgex v5.0.0) View Source

Cleans tables in a database represented by an Ecto repo.

Usage

Here's a basic example:

Surgex.DatabaseCleaner.call(MyProject.Repo)
Surgex.DatabaseCleaner.call(MyProject.Repo, method: :delete_all)
Surgex.DatabaseCleaner.call(MyProject.Repo, only: ~w(posts users))
Surgex.DatabaseCleaner.call(MyProject.Repo, only: [Post, User])
Surgex.DatabaseCleaner.call(MyProject.Repo, except: [Project])

This module may come in handy as a tool for configuring integration tests. You may use it globally if you want to clean before all tests as following:

setup do
  :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyProject.Repo)

  # ...

  Surgex.DatabaseCleaner.call(MyProject.Repo)

  :ok
end

Also, in order not to ruin test performance and the general experience of the Ecto sandbox, you may want to clean repo only after those tests that are tagged not to run in the sandbox. It can be achieved via the following on_exit callback:

setup do
  if tags[:sandbox] == false do
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyProject.Repo, sandbox: false)

    on_exit(fn ->
      :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyProject.Repo, sandbox: false)
      Surgex.DatabaseCleaner.call(MyProject.Repo)
    end)
  else
    # ...
  end

  :ok
end

Link to this section Summary

Functions

Cleans selected or all tables in given repo using specified method.

Link to this section Functions

Cleans selected or all tables in given repo using specified method.

Options

  • method: one of :truncate (default), :delete_all
  • only: cleans specified tables/schemas (defaults to all tables)
  • except: cleans all tables/schemas except specified ones