Chapter 14. Testing in Elixir and Phoenix

 

This chapter covers

  • Writing tests for simple Elixir functions
  • Writing tests for Phoenix interactions
  • Using doctests to simultaneously document and test your functions

Some developers love them and write them before writing anything else, and some developers can only barely stomach them. But even developers who’d rather not write a single one can agree that they’re helpful and can be critical to a healthy application. What can cause such extremes of emotion? Tests!

Tested code can help a developer sleep better at night. Tested code allows a developer to refactor code while being confident that no regressions occur. But testing can also be tedious and time-consuming. If you’ve had bad experiences with tests in the past, I have good news for you: testing Elixir code is a first-class concern, and the Elixir standard library contains a number of helpful utilities to help make sure your code isn’t only well tested, but also well documented.

For starters, a fantastic testing library called ExUnit is included with Elixir’s standard library.

14.1. An introduction to ExUnit

I have a surprise for you: your application already has tests! Don’t believe me? Try running mix test from the top of your application (auction_umbrella/). You’ll likely see some compilation notices and then, at the bottom, something like this:

Finished in 0.08 seconds
3 tests, 1 failure

14.2. Setting up tests for Ecto

14.3. Testing Ecto queries in Auction

14.4. Simultaneously writing documentation and tests with doctests

14.5. Writing tests For Phoenix

14.6. What next?

Summary