Elixir 1.20 type-checks deliberately wrong test calls
Sometimes you may need to pass a bad argument to a function to test that a guard rejects it:
def page(index) when is_integer(index) and index >= 0, do: ...test "rejects a non-integer index" do
assert_raise FunctionClauseError, fn -> MyApp.page(:invalid) end
endElixir 1.20 infers the argument type from the guard and puts a warning that :invalid can never match:
warning: incompatible types given to MyApp.page/1:
MyApp.page(:invalid)
given types:
:invalid
but expected one of:
sinteger() The test still passes, but if you run your suite with mix test --warnings-as-errors, the run will be aborted with an error.
Hide the value from the type checker
We can create a small helper that can hide a bad argument from the type checker with an identity function:
defmodule MyApp.Untyped do
# Identity at runtime. Its only job is to stand between a test's
# deliberately wrong value and the type checker.
def untyped(value), do: value
endLoad it from test_helper.exs and import it where needed:
Code.require_file("support/untyped.exs", __DIR__)
ExUnit.start()import MyApp.Untyped
test "rejects a non-integer index" do
assert_raise FunctionClauseError, fn -> MyApp.page(untyped(:invalid)) end
endThe guard still receives :invalid, but the type checker no longer complains about it.
It works with the current Elixir version, but unfortunately future versions may improve type inference and catch this pattern.