Today’s Tidbit: Elixir’s doc testing

So this is cool. Elixir allows you to define a simple test module like so:

defmodule DocTest do
use ExUnit.Case, async: true
doctest Unicorns
end

Which is cool and does things! But what exactly does it do? It runs code examples in documentation comments.(If you’re a Python user, I apologize for the headiness.)

Yes. You read that right. Automated testing of documentation examples! Let’s see an example:

defmodule Unicorns do
  @doc """
Gives a string unicorns.
## Examples
iex> Magic.unicorns("stephen")
"stephen unicorns"
iex> Magic.unicorns('silly')
"silly unicorns"
"""
def unicorns(str) when is_binary(str), do: str <> " unicorns"
def unicorns(str), do: to_string(str) <> " unicorns"
end

And run it:

$ mix test test/doc_test.exs
Finished in 0.00 seconds
1 test, 0 failures

Now, I should say: Mix generates the doctest macro in every new project, so it should already be there in your current apps. Time to start fleshing out that documentation, y’all!

For more:

http://elixir-lang.org/docs/stable/ex_unit/ExUnit.DocTest.html

Like what you read? Give Andrew Anderson a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.