Skip to content

Instantly share code, notes, and snippets.

@neenjaw
Forked from henrik/test_helper.exs
Created June 10, 2020 20:16
Show Gist options
  • Save neenjaw/5e5f752381798f55044c114c7cb037fd to your computer and use it in GitHub Desktop.
Save neenjaw/5e5f752381798f55044c114c7cb037fd to your computer and use it in GitHub Desktop.
Improved `assert_compile_time_raise` based on this comment by Andrea Leopardi: http://andrealeopardi.com/posts/compile-time-work-with-elixir-macros/#comment-2347206739
ExUnit.start()
defmodule CompileTimeAssertions do
defmacro assert_compile_time_raise(expected_exception, expected_message, fun) do
# At compile-time, the fun is in AST form and thus cannot raise.
# At run-time, we will evaluate this AST, and it may raise.
fun_quoted_at_runtime = Macro.escape(fun)
quote do
assert_raise unquote(expected_exception), unquote(expected_message), fn ->
Code.eval_quoted(unquote(fun_quoted_at_runtime))
end
end
end
end
@neenjaw
Copy link
Author

neenjaw commented Jun 10, 2020

assert_raise SomethingError, fn ->
quote do
# something
end
|> Code.eval_quoted()
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment