Testing Your Schema Through Database Calls

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing an Ecto Schema for Database Interacti ons | TOC | Setting Up Sandbox Mode 👉

While we have a decent basic schema defined, we haven’t covered a subset of the kinds of logic that you’ll find in changeset functions — code that requires interaction with the database to verify that it works. The validations we’ve tested so far have laid out a pattern for us that can be used with other validations beyond cast/3 and validate_required/2. Functions your code can call that can be tested in similar ways include (but are not limited to) validate_inclusion/4, validate_length/3, and validate_subset/4. A very common case where things are easier to test with a database is a unique constraint on a column in your database. In this section, we’ll add a new field to our schema and table, including such a constraint. We’ll review why it makes sense to pull the database into testing it, and then we’ll update the tests to show how to exercise that constraint.

You’ll recall that when we created our migration, we added a unique constraint on the email field. We also updated our changeset/1 function to include logic for this when we added unique_constraint/2. unique_constraint/2 is what we’ll focus on next. Before we test it, we should talk about what that function does.

The unique constraint is handled by the database, not by our changeset function. So why are we calling…

--

--

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.