Search⌘ K
AI Features

Testing Read Operation

Understand how to write tests for read operations in Elixir using Ecto queries and ExUnit. This lesson guides you through inserting test data, verifying successful data retrieval wrapped in success tuples, and handling error cases for non-existing records. You will gain practical skills in testing database reads to maintain data accuracy and application reliability.

We'll cover the following...

The Read function

First, let’s look at the code in our Users module at testing_ecto/lib/users/users.ex.

Note: 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.

Elixir
#file path -> testing_ecto/lib/users/users.ex
#add this code at the indicated place mentioned in comments of testing_ecto/lib/users/users.ex
#in the playground widget
def get(user_id) do
if user = Repo.get(User, user_id) do
{:ok, user}
else
{:error, :not_found}
end
end

Our ...