Refactoring to Increase Test Maintainability

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing Your Schema Through Changesets | TOC | Creating a SchemaCase for Shared Test Code 👉

Most applications that use Ecto have more than one schema, and over time each schema grows to have more fields or more logic in its changeset functions. We’re going to refactor our existing test file to allow our code to be easier to maintain, but that means we’re going to tread into some territory that makes some folk uncomfortable: we’re going to refactor our tests to be self-updating. We’ll build safety into the way we test to avoid a lot of the typical caveats that leave most people burned by writing self-updating tests.

We want to make it clear that we don’t promote this style of testing wholesale across your application. We’re working in a section of our code that’s fairly predictable and limited in scope. Our schemas only carry the definition and changeset functions.

We’re going to create a new test file, testing_ecto/test/schemas/user_basic_schema_2_test.exs, but we’re going have it test the same schema code as our previous test file. We mentioned earlier that we were adding numbers into the test file names that would break the convention of matching the test and application file names. Even though we called this a refactor, it’s probably best to create a second file, too, because doing so will make it easier to follow along with the book.

--

--

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.