Last active
June 10, 2020 20:16
-
-
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
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
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 |
This works:
assert_raise SomethingError, fn ->
quote do
# something
end
|> Code.eval_quoted()
end
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
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.