Test Driven Development with Elixir

William Vincent
2 min readOct 21, 2021

What is Test Driven Development

Test Driven Development, often shortened to TDD, is a development paradigm that stresses that test specs should be written for every line of code in a project. Often with an emphasis on writing a test for a function before you even write that function.

The strength of this paradigm is that instead of accumulating technical debt and making a codebase increasingly harder to maintain and changes harder to make, by ensuring that every function has a test you can easily ensure that any new code works as intended by simply running the every growing list of specs.

The challenge of TDD

This paradigm paints a glowing picture of maintainable code that is simple to extend into new features. However, it can be a challenge to keep pace with development requirements if every time you need to write a function you need to write a new test.

Importing the needed libraries, writing the library specific blocks of code, and ensuring that all the imports/exports are lined up correctly involves a lot of context switching, which can cause productivity to grind to a halt.

Elixirs answer to easy testing

Elixir handles testing in an interesting way that is tied to their @doc annotations. When you write a function doc and include an example of how the code should work, mix test will automatically use that example as a unit test for the function.

@doc """
Accepts a list as an argument. Returns a
list with the elements of the
first list in a different order.
## Examples iex> deck = Cards.create_deck
iex> new_deck = Cards.shuffle(deck)
iex> deck == new_deck
false
"""
def shuffle(deck) do
Enum.shuffle(deck)
end

The above code block does not only generate documentation for the function (as seen in this) but also handles the unit test for the function. This solution manages to completely avoid context switching and combines two tedious tasks, documentation and testing. I highly recommend giving this workflow a try!

Credit to Stephen Grider and The Complete Elixir and Phoenix Bootcamp. I am using this udemy course to learn the elixir language and it has been great so far, definitely recommend if you want some help learning to use elixir.

Check this story out on my personal blog!

--

--