Search⌘ K

Refactoring Tests to Be Self-updating

Explore refactoring Ecto schema tests to be self-updating by creating dynamic helper functions that generate valid parameters using Faker. Understand how these tests adapt automatically to schema changes, simplifying maintenance and ensuring thorough coverage as schemas evolve in Elixir applications.

Now that we have guaranteed our test’s accuracy in the previous lesson let’s refactor our test to be self-updating.

Creating a self-updating test

Before we write our first test, we’ll write a helper function at the bottom of our test file after all the describe blocks.

Helper function

The new function will be called valid_params/1:

Elixir
#file path -> testing_ecto/test/schemas/user_basic_schema_2_test.exs
#add this code at the indicated place mentioned in comments of
#testing_ecto/test/schemas/user_basic_schema_2_test.exs
#in the playground widget
defp valid_params(fields_with_types) do
valid_value_by_type = %{
date: fn -> to_string(Faker.Date.date_of_birth()) end,
float: fn -> :rand.uniform() * 10 end,
string: fn -> Faker.Lorem.word() end
}
for {field, type} <- fields_with_types, into: %{} do
{Atom.to_string(field), valid_value_by_type[type].()}
end
end

The return value of this function is a map that’s functionally identical to the params we had in our success test in our previous iteration of this file (user_basic_schema_1_test.exs). It’s just a string-keyed map of valid parameters, but it’s built dynamically based on the list of fields and types passed to it.

Faker

We’re using a new library, Faker:

Faker’s sole purpose is to provide realistically shaped data, often to use as fake data for ...