mmag

ハマったことメモなど

ExUnitのdescribeとnamed setupについてもう少し丁寧に

今日の昼に書いたエントリはとても雑だったので、もう少し丁寧に書きます。

describe

describe/2マクロを使うことで、複数のテストケースをまとめることができます。

defmodule MyAppTest do
  use ExUnit.Case, async: true

  describe "addition" do
    test "1 + 2 = 3" do
      assert 1 + 2 == 3
    end

    test "6 + 8 = 14" do
      assert 6 + 8 == 14
    end
  end
end

setup/1,2をdescribe毎に設定することができます。以下の例では、setup_all/1が返したmapとsetup/1が返したmapがマージされ、test/3で利用できます。

defmodule MyAppTest do
  use ExUnit.Case, async: true

  setup_all do
    %{one: 1}
  end

  describe "addition" do
    setup do
      %{two: 2}
    end

    test "1 + 2 = 3", %{one: one, two: two} do
      assert one + two == 3
    end
  end
end

制限

  • describe/2の内側でdescribe/2を使うことはできません。
  • describe/2の内側でsetup_all/1,2を使うことはできません。

named setup

setup/1, setup_all/1の引数に、ブロックではなく、atomatomのリストを渡すことができます。

defmodule MyAppTest do
  use ExUnit.Case, async: true

  setup_all :define_one

  describe "addition" do
    setup [:define_two, :define_three]

    test "1 + 2 = 3", %{one: one, two: two, three: three} do
      assert one + two == three
    end
  end

  def define_one(_context), do: %{one: 1}

  def define_two(_context), do: %{two: 2}

  def define_three(_context), do: %{three: 3}
end

複数のdescribeで同じ内容のsetupを行いたいときなどに有用です。