LoginSignup
1
2

More than 5 years have passed since last update.

ExUnit実行制御チートシート

Last updated at Posted at 2017-11-29

基本

  • すべてのテスト実行: mix test
  • 指定したファイルのテストを実行: mix test test/my_test.exs

実行するテストの制御

hoge_test.exs
defmodule HogeTest do
  use ExUnit.Case
  @moduletag :something

  describe "foo" do
    @tag :important
    test "test1"  do: # テストコード
    @tag :external
    test "test2"  do: # テストコード
  end
  describe "bar" do
    @tag :pin
    test "test1"  do: # テストコード
    @tag :skip
    test "test2"  do: # テストコード
  end
end
fuga_test.exs
defmodule FugaTest do
  use ExUnit.Case
  @moduletag :pending

  describe "foobar" do
    test "test"  do: # テストコード
  end
end

指定したテストのみを実行

  • タグ: mix test --only important
    • 複数も指定可能: mix test --only important --only pin
  • モジュールタグ: mix test --only something
  • test: mix test --only test:"test foo test1"
    • test [describe名] [test名]を指定
  • describe: mix test --only describe:"foo"
  • モジュール: mix test --only case:FugaTest

他にもExUnit側で用意されているタグがある。
詳しくは HexdocsのExUnit.Case中のKnown tagsを参照。

テストをスキップ

  • タグ: mix test --exclude important
    • skipタグ(@tag skip)が付いているテストは特に指定しなくてもスキップされる
  • describe、モジュール等も「指定したテストを実行」する場合と同様

特定のタグをデフォルトでスキップ

test/test_helper.exsにデフォルトでスキップするタグを指定できる

test/test_helper.exs
# 実用例: 次のタグの付いたテストはデフォルトでスキップ
# - external(外部サービスに依存するテストに付ける想定)
# - pending(一旦実行から除外するテストにつける想定)
ExUnit.configure(exclude: [:external, :pending])
ExUnit.start

デフォルトでスキップしたテストを含めて実行

  • externalも含めて実行: mix test --include external

その他

  • 前回失敗したテストのみ実行: mix test --stale
  • テストの詳細を出力: mix test --trace

余談

includeとexcludeの組み合わせの制約

includeとexcludeを併用した場合、以下のような処理になる。
1. excludeで該当するテストをスキップ対象にする
2. excludeでスキップ対象にされたテストのうちincludeに該当するテストを追加

結果として、次のようになる。

  • excludeは除外、ただしincludeは除外しない」は実現できる
  • includeしたものは除外しない、ただしその中でexcludeしたものは除外」は実現できない

例えば、このようなコードがあった場合、

some_test.exs
defmodule SomeTest do
  use ExUnit.Case
  @moduletag :external

  describe "foo" do
    @tag :important
    test "test1"  do: # テストコード
    @tag :pending
    test "test2"  do: # テストコード
  end
end
  • mix test --exclude external --include importantとすれば、このモジュール全体は除外するが、importantのついたテストは実行する、となる。
  • デフォルトでexternalを除外してあるとして、 mix test --include external --exclude pendingとやってexternalは実行しつつ、pendingを除外しようとしても、pendingの付いたテストも実行されてしまう。

onlyの仕組みと制約

onlyincludeexcludeの組み合わせで実装されている。
内部的には次のような処理になる。

  1. --exclude testですべてのテストをスキップ対象にする
    • ※すべてのテストには自動でtestタグが付いている
  2. --include [タグ]で指定のタグが付いたテストだけがスキップ対象から外れる

そのため、onlyもinclude、excludeの組み合わせの制約を受ける。
some_test.exsの例でmix test --only external --exclude pendingとしてもpendingタグが付いたテストはスキップされない。

1
2
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
1
2