Last active
January 7, 2022 04:13
-
-
Save wulymammoth/6a3cb9eed75620b6c05b949548559c8b to your computer and use it in GitHub Desktop.
chained/pipeline assertions in elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule TestHelper do | |
defmacro __using__(_opts) do | |
quote do | |
import ExUnit.Assertions, only: [assert: 1] | |
# we can name this whatever we'd like, | |
# but "is" makes sense to me in most cases | |
# π | |
def is(result, expectation) do | |
assert result == expectation | |
result # π allows us to continue chaining assertions in a pipeline | |
end | |
# this one allows us to make more complex assertions | |
# e.g., asserting that a nested key is of a particular value | |
def has(result, assertion) when is_function(assertion) do | |
assert assertion.(result) == true | |
result | |
end | |
end | |
end | |
end | |
# test/adder_test.exs | |
defmodule AdderTest do | |
use TestHelper # π included here | |
test "add" do | |
1..3 | |
|> Enum.map(& &1 * 2) | |
|> Adder.add(1) | |
|> is([3, 5, 7]) # π used here | |
|> has(&List.last(&1) == 7) # π and here (chained) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment