Testing Create Operation
Learn how to test queries in the testing_ecto application.
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:
Press + to interact
#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 widgetdef create(params) doparams|> 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:
Press + to interact
#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 widgetsetup doEcto.Adapters.SQL.Sandbox.checkout(TestingEcto.Repo)enddescribe "create/1" dotest "success: it inserts a user in the db and returns the user" doparams = 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_dbmutated = ["date_of_birth"]for {param_field, expected} <- params,param_field not in mutated doschema_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)}"endexpected_dob = Date.from_iso8601!(params["date_of_birth"])assert user_from_db.date_of_birth == expected_dobassert user_from_db.inserted_at == user_from_db.updated_atassert DateTime.compare(now, user_from_db.inserted_at) == :ltendend
Let’s go through our test step-by-step:
-
Observe the common setup block at line 7 ...