Testing Read

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing Create | TOC | Testing Update 👉

This next test is very simple. First, let’s take a look at the code in our Users module. We used “Read” in the section header to keep it in line with CRUD, but you’ll notice that we prefer to call our function get/1. This is entirely user preference.

testing_ecto/lib/users/users.ex

​ ​def​ get(user_id) ​do​
​ ​if​ user = Repo.get(User, user_id) ​do​
​ {​:ok​, user}
​ ​else​
​ {​:error​, ​:not_found​}
​ ​end​
​ ​end​

Our function isn’t a straight pass-through to the Ecto code. Instead, if the query returns a result, it wraps that result in a success (:ok) tuple, and if the user doesn’t exist, it returns an error tuple. Our tests will be pretty straightforward as well. For success, we’ll need to insert a user into the database before the exercise step. We’ll assert on the shape of the return value and then make sure that the actual data matches what was inserted into the database prior. The error test will try to “get” a user for a nonexisting ID. Open up your test file, testing_ecto/test/users/users_test.ex, and add the following describe block:

​1: describe ​"​​get/1"​ ​do​
​- test ​"​​success: it returns a user when given a valid UUID"​ ​do​
​- existing_user = Factory.insert(​:user​)
​-
​5: assert {​:ok​, returned_user} = Users.get(existing_user.id)
​-
​- assert returned_user ==…

--

--

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.