15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ExUnitのdescribeとnamed setup

Posted at

ブログから転載。


Elixir v1.3.0-rc.0から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の引数に、ブロックではなく、atomやatomのリストを渡すことができます。

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を行いたいときなどに有用です。

15
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?