为什么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 docs:https://hexdocs.pm/ex_machina/ExMachina.Ecto.html#c:params_for/2
答案 0 :(得分:0)
如果params
包含小写的postal_code
,它会被变更集提升。但是,Repo.get_by(Company, params)
仍会查找小写邮政编码,并返回nil