Testing Update

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing Read | TOC | Testing Delete 👉

Testing update is a bit of a combination of the testing for the create and read functions. Let’s first look at the function we’re going to test:

testing_ecto/lib/users/users.ex

​ ​def​ update(%User{} = existing_user, update_params) ​do​
​ existing_user
​ |> User.update_changeset(update_params)
​ |> Repo.update()
​ ​end​

You can see that, like create/1, this function is a very lightweight wrapper around calls to the schema’s changeset function (update_changeset/2 in this case) and then to Repo.update/1. Testing it will be similar, but you’ll need to insert an existing user to be updated by the code. Let’s write our success test first:

​1: describe ​"​​update/2"​ ​do​
​- test ​"​​success: it updates database and returns the user"​ ​do​
​- existing_user = Factory.insert(​:user​)
​-
​5: params =
​- Factory.string_params_for(​:user​)
​- |> Map.take([​"​​first_name"​])
​-
​- assert {​:ok​, returned_user} = Users.update(existing_user, params)
​10:
​- user_from_db = Repo.get(User, returned_user.id)
​- assert returned_user == user_from_db
​-
​- expected_user_data =
​15: existing_user
​- |> Map.from_struct()
​- |> Map.drop([​:__meta__​, ​:updated_at​])
​- |> Map.put(​:first_name​, params[​"​​first_name"​])
​-
​20: for {field, expected} <…

--

--

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.