Hello!
I have to test a unique constraint for a user email and I’m getting just Ecto.ConstraintError but I just got the error only when is used apply_action/2
without it succeeds.
The test case with apply_action/1
:
test "when is given an already existing email, returns the error" do
existing_user = user_fixture()
invalid_params = %{@valid_params | email: existing_user.email}
changeset = User.registration_changeset(invalid_params)
{:ok, user_struct} = Ecto.Changeset.apply_action(changeset, :insert)
response = Repo.insert(user_struct)
assert {:error, changeset} = response
end
Receives:
1) test call/1 when is given an already existing email, returns the error (StoneExample.Account.CreateTest)
test/stone_example/account/create_test.exs:53
** (Ecto.ConstraintError) constraint error when attempting to insert struct:
* users_email_index (unique_constraint)
If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `unique_constraint/3` on your changeset with the constraint
`:name` as an option.
The changeset has not defined any constraint.
The test case just with Repo.insert/2
without back validations in the application level:
test "when is given an already existing email, returns the error" do
existing_user = user_fixture()
invalid_params = %{@valid_params | email: existing_user.email}
changeset = User.registration_changeset(invalid_params)
response = Repo.insert(changeset)
assert {:error, changeset} = response
assert errors_on(changeset) == %{email: ["Email already exists"]}
end
The test above succeed.