Livebook is a powerful tool for interactive Elixir notebooks, but when it comes to testing, many developers are surprised to learn that you can run ExUnit tests directly within a Livebook. This is especially useful for quick prototyping, trying out small test cases, or demonstrating testing concepts without scaffolding a full Mix project.

Setup

Livebook doesn’t create a Mix project by default, but you can still use ExUnit directly in a code cell. To start using ExUnit, you need to start the test framework manually and define your tests inline.

Here’s the basic setup:

ExUnit.start()

Then you can define and run a test case using ExUnit.Case and ExUnit.run/0:

defmodule MathTest do
  use ExUnit.Case, async: false

  test "addition works" do
    assert 1 + 1 == 2
  end

  test "subtraction works" do
    assert 5 - 3 == 2
  end
end

ExUnit.run()

When you evaluate the cell, the test results will be printed in the output section of the Livebook.

Notes

  • Use async: false to avoid concurrency issues within the notebook environment.
  • If you rerun a cell, you might see a warning like warning: redefining module MathTest. You can use Code.compiler_options(ignore_module_conflict: true) to suppress it:
Code.compiler_options(ignore_module_conflict: true)

Place that line before redefining any modules during development.

Example: testing a custom function

Suppose you're working with a utility function in the notebook:

defmodule StringUtils do
  def reverse_words(string) do
    string
    |> String.split(" ")
    |> Enum.reverse()
    |> Enum.join(" ")
  end
end

You can write and run a test like this:

defmodule StringUtilsTest do
  use ExUnit.Case, async: false

  test "reverses words in a sentence" do
    assert StringUtils.reverse_words("hello world from livebook") ==
           "livebook from world hello"
  end
end

ExUnit.run()

Conclusion

While Livebook is not a full testing framework, it's perfectly capable of running ExUnit tests for small modules and quick validation. This is ideal for experimenting with ideas or teaching Elixir concepts interactively.

If you need a more traditional testing environment, consider creating a Mix project and using mix test. But for fast feedback loops, Livebook is surprisingly effective.