对为什么 Elixir Ecto 验证测试不起作用感到困惑

Confused about why an Elixir Ecto validation test is not working

我有一个如下所示的用户模型:

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

只有测试失败,即使密码太短了一个字符。我错过了什么?

您在创建变更集时拒绝了 password 字段。 这使得对该字段的验证甚至不会被触发。

您需要将 password 添加到您的 @required_fields@optional_fields 列表中。