Search⌘ K
AI Features

Testing Create Operation

Explore how to write tests for the create operation in Ecto queries using ExUnit. Understand how to verify successful data insertion and handle error scenarios effectively. Learn the importance of testing both return values and side effects to ensure data integrity in your Elixir applications.

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:

  • create/1
  • get/1
  • update/2
  • delete/1

The file lib/users/users.ex in testing_ecto is provided:

create/1

The create/1 function in testing_ecto/lib/users/users.ex look like this:

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 create(params) do
params
|> User.create_changeset()
|> Repo.insert()
end

It’s pretty basic, as most CRUD queries are. As a result, testing it won’t be very complicated, either.

Writing tests

Let’s set up a new file at testing_ecto/test/users/users_test.ex.

Success path test

First, we’ll write a success path test.

In it, set up a basic test file structure and then add a describe block for create/1 and our first test:

Elixir
#file path -> testing_ecto/test/users/users_test.exs
#add this code at the indicated place mentioned in comments of testing_ecto/test/users/
#users_test.exs in the playground widget
setup do
Ecto.Adapters.SQL.Sandbox.checkout(TestingEcto.Repo)
end
describe "create/1" do
test "success: it inserts a user in the db and returns the user" do
params = Factory.string_params_for(:user)
now = DateTime.utc_now()
assert {:ok, %User{} = returned_user} = Users.create(params)
user_from_db = Repo.get(User, returned_user.id)
assert returned_user == user_from_db
mutated = ["date_of_birth"]
for {param_field, expected} <- params,
param_field not in mutated do
schema_field = String.to_existing_atom(param_field)
actual = Map.get(user_from_db, schema_field)
assert actual == expected,
"Values did not match for field: #{param_field}\nexpected: #{
inspect(expected)
}\nactual: #{inspect(actual)}"
end
expected_dob = Date.from_iso8601!(params["date_of_birth"])
assert user_from_db.date_of_birth == expected_dob
assert user_from_db.inserted_at == user_from_db.updated_at
assert DateTime.compare(now, user_from_db.inserted_at) == :lt
end
end

Let’s go through our test step-by-step:

  • Observe the common setup block at ...