Reputation: 11089
I have a user model that looks like this:
defmodule MyApp.User do
schema "users" do
field :name, :string
field :email, :string
field :password, :string, virtual: true
field :password_confirmation, :string, virtual: true
timestamps
end
@required_fields ~w(name email)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> validate_length(:password, min: 8)
end
end
And the test in question makes sure the password length validation works.
defmodule MyApp.UserTest do
use MyApp.ModelCase
alias MyApp.User
alias MyApp.Repo
@valid_attrs %{
name: "Uli Kunkel",
email: "[email protected]",
}
@invalid_attrs %{}
test "validates the password is the correct length" do
attrs = @valid_attrs |> Map.put(:password, "1234567")
changeset = %User{} |> User.changeset(attrs)
assert {:error, changeset} = Repo.insert(changeset)
end
end
Only the test fails, even though the password is a character too short. What am I missing?
Upvotes: 2
Views: 917
Reputation: 11288
You're rejecting the password
field when creating the changeset.
This makes it so the validation on that field is not even triggered.
You need to add password
to either your @required_fields
or @optional_fields
list.
Upvotes: 4