Skip to content

Instantly share code, notes, and snippets.

@wulymammoth
Last active January 7, 2022 04:13
Show Gist options
  • Save wulymammoth/6a3cb9eed75620b6c05b949548559c8b to your computer and use it in GitHub Desktop.
Save wulymammoth/6a3cb9eed75620b6c05b949548559c8b to your computer and use it in GitHub Desktop.
chained/pipeline assertions in elixir
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