Testing Your Schema Through Changesets

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 4 Testing Ecto Schemas | TOC | Refactoring to Increase Test Maintainability 👉

As we mentioned, Ecto can be used for more than just database interactions, the most common case being as a validator of data. Either way you use it, there’s a common core of code in the schema file and therefore there are common tests. We’ll start by testing that common code, and then we’ll make some refactors to make our tests easier to maintain. After that, we’ll branch out and refactor our code and tests twice, once for each use case. We’ll call it out when it happens. This means that we’ll be working in very similar code but switching between file names to keep the concepts separate.

Our Ecto-based code and tests are going to be written to reflect the belief that schema files should contain a bare minimum of logic, usually just the schema definition and functions that are focused on translating data to or from that schema definition. If you like to put more logic in your modules, you’ll be on your own for testing it.

Ecto provides two modules, Ecto.Schema and Ecto.Changeset, that we’ll use to define our basic schema and core validation behavior. Ecto.Schema allows us to define (Ecto) structs and their types using a domain-specific language (DSL). Ecto.Changeset is code that, among other things, provides type casting and validation logic. When you define a schema with…

--

--

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.