Testing Create

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Adding a DataCase to Help with Setup | TOC | Testing Read 👉

We’re going to start by looking at part of the logic file with our queries. The file, called Users, contains the basic CRUD actions, in this case called create/1, get/1, update/2, and delete/1. We’ve provided a file in the copy of testing_ecto included with the book. You’re welcome to copy that over or type it in yourself. The file and the create/1 function look like this:

testing_ecto/lib/users/users.ex

​ ​defmodule​ TestingEcto.Users ​do​
​ @moduledoc false
​ alias TestingEcto.Repo
​ alias TestingEcto.Schemas.User

​ ​def​ create(params) ​do​
​ params
​ |> User.create_changeset()
​ |> Repo.insert()
​ ​end​
​ ​end​

It’s pretty basic, as most CRUD queries are. As a result, testing it won’t be very complicated, either. First we’ll write a success path test. Open up a new file at testing_ecto/test/users/users_test.ex. In it, we’ll set up a basic test file structure and then add a describe block for create/1 and our first test:

testing_ecto/test/users/users_test.exs

​1: ​defmodule​ TestingEcto.UsersTest ​do​
​- ​use​ TestingEcto.DataCase
​- alias TestingEcto.Users
​- alias TestingEcto.Schemas.User
​5:
​- setup ​do​
​- Ecto.Adapters.SQL.Sandbox.checkout(TestingEcto.Repo)
​- ​end​
​-
​10: describe ​"​​create/1"​ ​do​
​…

--

--

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.