Skip to content

Section 3 Lesson 29: Effective Doctests

Thiago Salles edited this page Jul 2, 2021 · 1 revision

Doctests allow us to generate tests from code examples found in @moduledoc and @doc attributes.
To do this, invoke the doctest/1 macro from within your test case and ensure your code examples are written according to the syntax and guidelines.

Take a look at the following test file:

defmodule AppTest do
  use ExUnit.Case
  doctest App

  test "greets the world" do
    assert App.hello() == :world
  end
end

With the function definition bellow, two tests will be run:

@doc """
  Doubles the given number

## Examples

    iex> App.double(1)
    2

    iex> App.double(128)
    256

"""
def double(number) do
  number * 2
end

The pattern is:

  • Something with iex> before will be executed
  • Something without iex> will be checked against the previous execution result to match
  • Line breaks between examples tell Elixir they are different doctest cases

To disable doctest from a single function in the module, use the exclude param on doctest/1 macro, passing a list of {function, arity} tuples

  doctest App, exclude: [random: 1]

Reference: https://hexdocs.pm/ex_unit/ExUnit.DocTest.html