Search⌘ K

Applying Named Setup Functions to Our Tests

Explore how to implement named setup functions for your Elixir tests to manage test complexity and reuse setups. Understand the benefits of grouping tests with context keys and creating predictable test data, enabling clearer and more maintainable test suites.

With the trade-offs in mind, we will choose to write some named setups to achieve the following:

  • Control duplication.

  • Simplify each test block.

Responses

Let’s start with /test/response_test.exs since it’s complex enough to need named setups, but simple enough to illustrate the concept.

The first step is to create the file with the basic heading, like this:

C++
defmodule ResponseTest do
use ExUnit.Case
use QuizBuilders
end

We use the QuizBuilders macro to build in our fixtures.

Next, we’ll build some simple local functions to build a quiz with the exact quiz and templates we need. We’ll fill them in /test/response_test.exs, like this:

C++
defp quiz() do
fields = template_fields(generators: %{left: [1], right: [2]})
build_quiz()
|> Quiz.add_template(fields)
|> Quiz.select_question
end
defp response(answer) do
Response.new(quiz(), "mathy@example.com", answer)
end
  • Since we’re testing for correct responses, we want a repeatable template with only one possible ...