Skip to content

Instantly share code, notes, and snippets.

@koga1020
Last active October 8, 2022 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koga1020/f0a0d924a3f11edd87dac5146cb52e98 to your computer and use it in GitHub Desktop.
Save koga1020/f0a0d924a3f11edd87dac5146cb52e98 to your computer and use it in GitHub Desktop.

assert_matchを試す

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}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment