Creating a Factory to Help with Setup

Testing Elixir — by Andrea Leopardi, Jeffrey Matthias (47 / 80)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 5 Testing Ecto Queries | TOC | Adding a DataCase to Help with Setup 👉

In testing, we create factories to give ourselves consistent, repeatable ways to provide data for our setup phase. One of the areas where this kind of tooling is the most useful is when interacting with the database.

When we write tests that interact with database tables, we need two sets of data that are either valid or invalid with regard to the table’s definition. As our applications grow larger, we’ll find that having a single source of setup data helps us keep the test suite maintainable. If we update our schema definition, that single source is often the only place (aside from the tests for the schema file itself) that’ll need to be updated in your test suite.

It’s totally possible to write a factory for your application entirely from scratch. When we were testing our Ecto schemas, we started to do that by creating a helper function called valid_params. It took a set of fields and types and returned a set of randomized parameters that met the minimum requirements of the schema’s definition. That function has some notable limitations, however. It was written to be generic and therefore the data it returns isn’t very specific to the exact field for which it’s making the data. An example is that since the email field was a string, the function returned a single word string, not an…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.