Search⌘ K
AI Features

Set Up an Async Test

Explore how to configure the Ecto Repo to use a sandbox pool in the test environment and write async test cases in Elixir. Learn to set the correct ownership mode and checkout sandbox connections to safely run tests concurrently, improving test suite efficiency.

Change the Repo config to use the sandbox

We need to change our Repo configuration to use the sandbox pool in order to take advantage of the sandbox. We only want to do this when we’re in our test environment, though. That’s why we make the following change in config/test.exs and only there.

Elixir
config :music_db, MusicDB.Repo,
pool: Ecto.Adapters.SQL.Sandbox
# other settings here

When we change the pool: setting, we’re telling Ecto that we’ll not be using the default connection pool and instead give the sandbox complete control over how connections are checked out and used by processes.

Correct the ownership mode

Next, we need to set our sandbox to the correct ownership mode. We’ll cover this setting in more detail later, but for now, we add this line to test/test_helper.exs.

Elixir
Ecto.Adapters.SQL.Sandbox.mode(MusicDB.Repo, :manual)

Write the test case

Now we’re ready to write our test case. We create a file called test/album_test.exs and add the following code.

Elixir
defmodule MusicDB.AlbumTest do
use ExUnit.Case, async: true
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(MusicDB.Repo)
end
test "insert album" do
album = MusicDB.Repo.insert!(%MusicDB.Album{title: "Giant Steps"})
new_album = MusicDB.Repo.get!(MusicDB.Album, album.id)
assert new_album.title == "Giant Steps"
end
end

Notice that we set async: true on the first line of the test. This tells Elixir that it’s safe to run this test concurrently with other tests.

We also added a setup block that calls the checkout function on the sandbox. This is how we obtain the database connection we’ll be using throughout our test. We need to make this call because we set the ownership mode to :manual in our test helper, but that’s not the case for all ownership modes.

Try it out

import Config
Creating an asynchronous test using a sandbox