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.
We'll cover the following...
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.
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.
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.
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