0

为什么 params_for 不通过变更集模型是主要问题。params_for 为 postal_code 生成 4 个数字和 2 个字母(可以是小写或大写)。如果 params_for 将通过变更集,则之后将全部大写。为什么这个测试目前失败了?

错误信息:Expected truthy, got nil

我有一个公司模型,带有这个变更集:

def changeset(company, params \\ %{}) do
  company
  ...
  |> maybe_sanitize_postal_code(:postal_code)
  ...
end

defp maybe_sanitize_postal_code(changeset, attr) do
  case get_change(changeset, attr) do
    nil -> changeset
    postal_code -> put_change(changeset, attr, sanitize_postal_code(postal_code))
  end
end

defp sanitize_postal_code(postal_code) do
  postal_code
  |> String.replace(~r/\s+/, "")
  |> String.upcase()
end

我有这个测试:

test "create company with postal code", %{conn: conn, user: user} do
  params = params_for(:company)
  conn = post conn, company_path(conn, :create), company: params
  assert json_response(conn, 201)["company"]["id"]
  company = Repo.get_by(Company, params)
  assert company
  assert [user] == Repo.all Ecto.assoc(company, :users)
  ...
end

params_for 文档:https ://hexdocs.pm/ex_machina/ExMachina.Ecto.html#c:params_for/2

4

1 回答 1

0

如果params包含 lowercased postal_code,它会被变更集大写。但是,Repo.get_by(Company, params)仍然寻找小写的邮政编码,返回nil

于 2017-09-12T15:35:01.773 回答