Share Setup Data in ExUnit


Here's how to share setup data between test cases in ExUnit.

Expensive tests tend to want to do many assertions in one case.

Then you end up with this, where everything's crammed into one test case:

test "generic desc" do
  # many set up steps

  # asserting thing one
  assert(one_thing == "one")

  # asserting thing two
  assert(another_thing == "two")
end

But you can use the things that ExUnit provides to organize this better.

setup returns a result tuple where the value is a context that can be a keyword list or map

setup do
  # many set up steps
  {:ok, thing_from_setup: "one", another_thing: "two"}
end

Then in your cases, you can access it with a context map. This allows splitting into a clearer set up and assertions with descriptions in the test cases instead of comments and with nice split-up block scopes:

test "thing one", %{thing_from_setup: thing_from_setup} do
  assert("one" == thing_from_setup)
end

test "thing two", %{another_thing: another_thing} do
  assert("two" == another_thing)
end

Nicer, eh?