Sunday 12 February 2017

ExUnit test descriptions

Two things I like:

  1. Getting things done.
  2. Attention to detail.

I have been writing a fair few tests recently for various phoenix projects using describe blocks. I started using describe blocks mostly as a connivence to run certain setup functions for a given describe block…

defmodule Foo.BarTest do
  use Foo.ConnCase


  describe "A broad description of the tests"
    setup [
      :start_api,
      :default_fixture,
      :custom_fixtures
    ]

    test "something specific that should be a 302" do
       # build a response
        resp = build_conn() |> post("/foo", %{bar: "baz"})
       
       # it was a 302
       assert 302 == resp.status_code
    end
  end
end

What was not apparent to me was the way that when the tests fail, the string from the top of the description block and the test is concatenated. So when a test fails I noticed this

>>  mix test test/controllers/foo_controller_test.exs
 1) test A broad description of the tests something specific that should be a 302 (Foo.FooControllerTests)
....
2 tests, 1 failure

Because I had written the two strings without knowing this, the feedback I was getting made no sense. But with a subtle tweak it did make sense…

defmodule Foo.BarTest do
  use Foo.ConnCase


  describe "/foo behaves as expected when..."
    setup [
      :start_api,
      :default_fixture,
      :custom_fixtures
    ]

    test "POST bar=baz" do
       # build a response
        resp = build_conn() |> post("/foo", %{bar: "baz"})
       
       # it was a 302
       assert 302 == resp.status_code
    end
  end
end

Which then produces feedback like this

>>  mix test test/controllers/foo_controller_test.exs
 1) /foo behaves as expected when... POST bar=baz (Foo.FooControllerTests)
....
2 tests, 1 failure

And that, I think, is lovely attention to detail which helps me get things done.