mmag

ハマったことメモなど

ExUnitで特定のテストだけ実行・スキップする方法

特定のテストだけ実行する

ファイル単位で指定して実行する

mix testに引数を渡すことで、そのファイルだけテストを実行できます。

$ mix test test/my_test.exs

行番号を指定して実行する

ファイル単位の指定に加えて、:5のように行番号を指定できます。

$ mix test test/my_test.exs:5

タグ単位で指定して実行する

モジュール属性として@tag :hoge、または@tag hoge: trueをつけ、mix test--onlyオプションを渡すと、そのタグが付与されたテストだけを実行できます。@moduletagでも同様のことが可能です。

defmodule FirstTest do
  use ExUnit.Case, async: true

  test "..." do
    ...
  end

  @tag :need_database
  test "..." do
    ...
  end
end
defmodule SecondTest do
  use ExUnit.Case, async: true

  @moduletag :need_database

  ...
end
$ mix test --only need_database

前回failしたテストだけ実行する

v1.3から入る機能ですが、--staleオプションをつけることで前回落ちたテストだけを再度実行することができます。 間違い。前回テストを実行したとき以降に変更を加えたモジュールが影響するテストだけ実行できます。

$ mix test --stale

特定のテストだけスキップする

モジュール単位でスキップする

@moduletag :skip、または@moduletag skip: trueを書くと、それ以降のtestが全てスキップされます。

defmodule MyTest do
  use ExUnit.Case, async: true

  @moduletag :skip

  ...
end

個別にスキップする

@tag :skip、または@tag skip: trueを書くと、その直後のtestがスキップされます。

defmodule MyTest do
  use ExUnit.Case, async: true

  @tag :skip
  test "hoge" do
    ...
  end

  test "fuga" do
    ...
  end
end

タグ単位で指定してスキップする

--excludeオプションを付与することで、特定のタグが付いたテストをスキップすることができます。

$ mix test --exclude need_database

自動で付与されるタグ

ExUnitによって付与されるタグがいくつか存在します。

  • :case
  • :file
  • :line
  • :test
  • :async
  • :type
  • :registered
  • :describe

以下のタグは、自分で設定することで便利に使えるものです。個別の詳細についてはまた別の機会に。

  • :capture_log
  • :skip
  • :timeout
  • :report

これらのタグも--onlyなどで利用できます。

$ mix test --only case:MyAppTest

余談ですが、実際には--only--include--excludeの合わせ技のためのショートカットのようなもので、以下の2つは等価です。testタグは全てのテストに付与されるので、それを除外した上で、need_databaseタグが付いたものをテストする、という意味です。

$ mix test --only need_database
$ mix test --include need_database --exclude test