How To Write Phoenix and Elixir Doc Tests

April 18, 2017

How To Write Phoenix and Elixir Doc Tests

Over the course of a couple of weeks of working with Phoenix and Elixir, I was asked to document and possibly provide some tests with respect to a code base I was working on.

Elixir basics

It’s actually pretty straightforward to setup.

Step 1: Set up a documentation block

First setup a documentation block in the module you are testing.

@doc """
Return a base url to query the YT api

## Example
  iex> Yt.fetch_url("playlists")

  iex> Yt.to_integer_or_default("4")

Add the iex> prompt just like in the above code with a call to the method you’re testing. On the next line, there should be the result you’re expecting.

Step 2: Add “doctest” to your test file with the module name as an argument

In my case, I created a file in test/documenation_test.exs.

defmodule DocumentationTest.Test do
  use ExUnit.Case
  doctest Yt

Step 3: Make sure the method you’re testing is public

You can’t test private methods, so don’t bother.

Step 4: Run the tests

Run your documentation tests just like you would any other test.

mix test test/documentation_test.exs

You should see successful output if your tests passed.


Documentation based testing is a handy way to test and document your Phoenix application at the same time. Give it a try!