为什么 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