...
/Refactoring Tests to Be Self-updating
Refactoring Tests to Be Self-updating
Learn how to write self-updating tests for a basic schema.
We'll cover the following...
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
:
#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 widgetdefp valid_params(fields_with_types) dovalid_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].()}endend
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 ...