Organizing Our Tests using Setup Blocks

Let’s look into how we can organize our tests using ExUnit's Setup Blocks and make our test suite easier to maintain.

We'll cover the following

Setup blocks

While an individual test can contain its own setup code, sometimes we realize we’re writing the same setup over and over. This situation is an opportunity to consider a setup block instead. The code in a setup block will be executed before each test inside its scope. Since the code has the same name as the stage in the test design, we’ll call the executable code a setup block while referring to the stage of testing as setup.

A setup block needs to return a value that makes sense for what comes after it. If the setup is to set state elsewhere and none of the values are useful in the tests following it, the return value can be as simple as :ok. The return value from a setup block is often passed to the tests it precedes.

Let’s look at an example of a setup block where no state is changed, but we’ve decided that we don’t want to redefine the same anonymous functions for each test.

Get hands-on with 1400+ tech skills courses.