William Schroeder
William Schroeder
Nov 1, 2022 2 min read

Run Elixir Tests in Interactive Elixir

If you enjoy REPL-driven development with Elixir, you may be delighted to know that you can iteratively develop your tests without rerunning mix or iex.

First, start iex with the test environment:

MIX_ENV=test iex -S mix

I like to use this one-liner for running an entire test file, since it is easy to just hit the up arrow and rerun it quickly:

recompile; Code.compile_file("test/my_test.exs"); ExUnit.run

If I need to run a test starting at a specific line, I leverage ExUnit.configure/1, which will exclude running all tests and instead run the test at line 20:

recompile; Code.compile_file("test/my_test.exs"); ExUnit.configure(exclude: [:test], include: [line: "20"]); ExUnit.run()

A quick overview of the API involved:

  • recompile: This is the cornerstone of Elixir’s REPL-driven development; it will detect changed files and recompile them as necessary. This does not include the files in the test directory. Note that config changes will require a complete restart of iex. There are no silver bullets.
  • Code.compile_file/1: This not only ensures the file is compiled to bytecode, but it also registers or re-registers the test with ExUnit. Without this command, ExUnit does not know what tests are available to run this iteration.
  • ExUnit.configure/1: This is what is ultimately passed the parameters passed to mix test. The last example above is equivalent to
    mix test test/my_test.exs:20
    
  • ExUnit.run/0: This runs the test suite, based on what tests are currently registered. Once it is done, the tests are no longer registered.