Creating a SchemaCase for Shared Test Code

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Refactoring to Increase Test Maintainability | TOC | Testing an Ecto Schema as a Data Validator 👉

Case templates are very useful when we identify a pattern for test files that would benefit from shared code. Our refactors on the basic schema tests created two helper functions, valid_params/1 and invalid_params/1, that would be good to move into a common place to be reused by all our schema tests. We’ll create a case template called SchemaCase and move the helper functions there. Create a new file called testing_ecto/test/schema_case.ex and add the basic structure for a case template:

testing_ecto/test/schema_case.ex

​ ​defmodule​ TestingEcto.SchemaCase ​do​
​ ​use​ ExUnit.CaseTemplate

​ using ​do​
​ ​quote​ ​do​
​ alias Ecto.Changeset
​ ​import​ TestingEcto.SchemaCase
​ ​end​
​ ​end​

​ ​end​

For now, it’s pretty simple. We can alias Ecto.Changeset into the case template because all future schema tests will need it. We have import TestingEcto.SchemaCase included; so when we add the helper functions, anything that “uses” the template will get those functions. Our last step is to copy the two functions, valid_params/1 and invalid_params/1, into the file, below the “using” block. Just be sure to make both functions public (def instead of defp), as import only works with public functions. The case…

--

--

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.