Skip to content

Instantly share code, notes, and snippets.

@leobessa
Forked from TylerPachal/custom_assert_04.ex
Last active October 27, 2023 02:36
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 leobessa/d738abd684e97ba6f4e90ea019c055fd to your computer and use it in GitHub Desktop.
Save leobessa/d738abd684e97ba6f4e90ea019c055fd to your computer and use it in GitHub Desktop.
@doc """
Asserts that the given changeset is invalid, and that when the
assertion_expression is applied to the error_message it results in a truthy
value.
"""
defmacro assert_invalid(changeset, field, assertion_expression) when is_atom(field) do
expr = Macro.to_string(assertion_expression)
quote do
error_messages = unquote(changeset)
|> Ecto.Changeset.traverse_errors(fn {message, _opts} -> message end)
|> Map.get_lazy(unquote(field), fn ->
flunk("field :#{unquote(field)} not found in errors")
end)
error_messages
|> Enum.any?(fn message ->
var!(error_message) = message
unquote(assertion_expression)
end)
|> unless do
flunk("""
Expression did not match error message
#{IO.ANSI.cyan()}error_message:#{IO.ANSI.reset()} #{inspect(error_messages)}
#{IO.ANSI.cyan()}expression:#{IO.ANSI.reset()} #{unquote(expr)}
""")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment