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:

lib/my_app.ex
def page(index) when is_integer(index) and index >= 0, do: ...
test/my_app_test.exs
test "rejects a non-integer index" do
  assert_raise FunctionClauseError, fn -> MyApp.page(:invalid) end
end

Elixir 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:

test/support/untyped.exs
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
end

Load it from test_helper.exs and import it where needed:

test/test_helper.exs
Code.require_file("support/untyped.exs", __DIR__)

ExUnit.start()
test/my_app_test.exs
import MyApp.Untyped

test "rejects a non-integer index" do
  assert_raise FunctionClauseError, fn -> MyApp.page(untyped(:invalid)) end
end

The 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.

← All notes