我有一个如下所示的用户模型:
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
有问题的测试确保密码长度验证有效。
defmodule MyApp.UserTest do
use MyApp.ModelCase
alias MyApp.User
alias MyApp.Repo
@valid_attrs %{
name: "Uli Kunkel",
email: "nihilist@example.com",
}
@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
即使密码太短,也只有测试失败。我错过了什么?
答案 0 :(得分:4)
您在创建变更集时拒绝password
字段。
这样就不会触发该字段的验证。
您需要将password
添加到@required_fields
或@optional_fields
列表中。