Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active June 10, 2020 20:16
Show Gist options
  • Save henrik/1054546364ac68da4102 to your computer and use it in GitHub Desktop.
Save henrik/1054546364ac68da4102 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
@henrik
Copy link
Author

henrik commented Nov 8, 2015

Since we're looking for a compile-time raise, just evaluating the function like this (as opposed to evaluating the function body, or evaluating a function call) should be enough.

@suazithustra
Copy link

This works:

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

@neenjaw
Copy link

neenjaw commented Jun 10, 2020

This is much later, but this discussion has been very helpful, thanks!

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