Testing Schema through Ecto Changesets

Get introduced to ecto schemas and learn how to test ecto schemas using changesets.

As we mentioned, Ecto can be used for more than just database interactions—it can be a validator of data. Either way, we 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 for each use case.

We’ll call it out when it happens. This means that we’ll work in a similar code but switch between file names to keep the concepts separate.

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 we define a schema with Ecto.Schema, we define a container for data, but code tests focus on behavior. On our first pass, we’ll test code using Ecto.Changeset functions under the hood to allow our tests to explore and validate both the schema’s definition and the behavior of a single function.

Note: Our Ecto-based code and tests will 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 them.

Get hands-on with 1200+ tech skills courses.