Tuesday, April 4, 2023

Elixir tips #2 - Doctest

A "hidden" gem of Elixir is the fact that you can actually test your documentation: yeah, you got it! you can test your documentation! 

Elixir makes documentation a first-class citizen in the language: it means documentation should be easy to write and easy to read.

If you are new about how to write Elixir documentation here the link .

We can now go directly to the concrete example. 

Let's start by creating a new project just by typing mix new doctest_demo :

If you now navigate to the lib and test folders you will find the following modules lib/doctest_demo and test/doctest_demo_test.exs (as described from the above output):

Without any further action let's run mix test and analyze the output:

Interesting fact is the output of mix test command: 1 doctest, 1 test, 0 failure. 

What does it mean 1 doctest
If you have a close look to line number 3 of test/doctest_demo_test.exs you will see the magic happens: doctest Doctestemo

With that syntax the code contained in the @doc snippet have been tested. How does it work? 

from official documentation:

Every new test starts on a new line, with an iex> prefix. Multiline expressions can be used by prefixing subsequent lines with either ...> (recommended) or iex>.

The expected result should start the line after the iex> and ...> line(s) and be terminated by a newline.

To run doctests include them in an ExUnit case with a doctest macro


Amazing! Did you know about it? We are actually making sure our documentation does not go out of date. 

Let's change the result of hello function to worlds and analyze what happens:

Niceee! doctest feature recognized that documentation is not aligned anymore with the code and it has been reported as error.

If you want to know more about it and its syntax and features here the link to the official documentation, enjoy it!