Adding a DataCase to Help with Setup

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Creating a Factory to Help with Setup | TOC | Testing Create 👉

When testing our Ecto schemas, we made a case template called SchemaCase. That was very specific to an exact kind of test. While the exercise of making that was useful, you’ll likely find that a slightly higher-level case template can cover your needs for anything that’s dealing with data as it’s needed for database interactions. We’re going to create a new case template that will look very similar and, if you took the time, would be able to replace the SchemaCase that we used in the schema tests. Create a new file called testing_ecto/test/data_case.ex and add the following code:

testing_ecto/test/data_case.ex

​1: ​defmodule​ TestingEcto.DataCase ​do​
​- ​use​ ExUnit.CaseTemplate
​-
​- using ​do​
​5: ​quote​ ​do​
​- alias Ecto.Changeset
​- ​import​ TestingEcto.DataCase
​- alias TestingEcto.{Factory, Repo}
​- ​end​
​10: ​end​
​-
​- setup _tags? ​do​
​- Ecto.Adapters.SQL.Sandbox.mode(TestingEcto.Repo, ​:manual​)
​- ​end​
​15: ​end​

Right now, using this file brings only two advantages over using ExUnit.Case. First, it provides the common sandbox setup, like our SchemaCase did in the last chapter. Second, it adds an alias for TestingEcto.Factory and TestingEcto.Repo on line 8. We’ll need both of those for our query tests. As you build…

--

--

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.