...
/Extensions to Creating a Self-Updating Test
Extensions to Creating a Self-Updating Test
Learn how to write self-updating tests for a basic schema.
We'll cover the following...
Before we write any more code, we’ll take our schema back to its previous state by removing the middle name field from the definition in the schema and from the @fields_and_types
in the test file (discussed in the previous lesson).
Further refactoring
First, we’ll update the test for the cast errors. To do this, we’ll add one more helper function, similar to valid_params/1
, but this time called invalid_params/1
. It’ll work similarly but will return values that can’t be cast for the field’s type.
#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 invalid_params(fields_with_types) doinvalid_value_by_type = %{date: fn -> Faker.Lorem.word() end,float: fn -> Faker.Lorem.word() end,string: fn -> DateTime.utc_now() end}for {field, type} <- fields_with_types, into: %{} do{Atom.to_string(field), invalid_value_by_type[type].()}endend
The function is constructed to work like valid_params/1
but to return values that can’t be cast to the matching types.
With this added, we can now write an updated version of our error test for casting. We’ll add the following test:
#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 widgettest "error: returns an error changeset when given un-castable values" doinvalid_params = invalid_params(@expected_fields_with_types)assert %Changeset{valid?: false, errors: errors} =UserBasicSchema.changeset(invalid_params)for {field, _} <- @expected_fields_with_types doassert errors[field], "The field :#{field} is missing from errors."{_, meta} = errors[field]assert meta[:validation] == :cast,"The validation type, #{meta[:validation]}, is incorrect."endend
Just like our previous test (user_basic_schema_1_test.exs
), this test is almost identical to the previous version, but now it includes a call to ...