Mix.install([
{:assert_match, github: "siiibo/assert_match"}
])
* Getting assert_match (https://github.com/siiibo/assert_match.git)
remote: Enumerating objects: 85, done.
remote: Counting objects: 100% (85/85), done.
remote: Compressing objects: 100% (44/44), done.
remote: Total 85 (delta 31), reused 68 (delta 21), pack-reused 0
origin/HEAD set to main
==> assert_match
Compiling 1 file (.ex)
Generated assert_match app
:ok
System.version()
"1.14.0"
試しに構造体とリストのパターンマッチをassert_matchを利用して書いてみます。
利用方法はassert_match本体のテストコードを見ると分かりやすいです。
import AssertMatch
を実行- あとは
assert_match/2
を使うだけ
という使い方のようです。
ExUnit.start()
defmodule User do
defstruct [:name, :age]
def build(attrs) do
%User{name: attrs.name, age: attrs.age}
end
end
defmodule SampleTest do
use ExUnit.Case
import AssertMatch
test "構造体のマッチ" do
attrs = %{name: "foo", age: 20}
# あえてpipeで書くとこんな感じ
attrs
|> User.build()
|> assert_match(%{age: 20})
|> assert_match(%{name: "foo"})
# これと同じ
assert %{age: 20} = User.build(attrs)
end
test "リストのマッチ" do
1..10//2
|> Enum.to_list()
|> assert_match([1, 3, 5 | _])
end
end
ExUnit.run()
..
Finished in 0.00 seconds (0.00s async, 0.00s sync)
2 tests, 0 failures
Randomized with seed 718926
%{excluded: 0, failures: 0, skipped: 0, total: 2}