如何解决Ecto断言#Ecto.Association.NotLoaded <关联:xyz未加载>
我通常检查我的测试是否返回预期的结果,像这样:
company = company_fixture() # inserts a company in the database with default attributes
assert Profile.get_company!(company.id) == company
但这失败了
Assertion with == failed
code: assert Profile.get_company!(company.id) == company
left: %MyApp.Profile.Company{
customers: [],employees: [],# more attributes,all matching
}
right: %Databaum.Profile.Company{
customers: #Ecto.Association.NotLoaded<association :customers is not loaded>,employees: #Ecto.Association.NotLoaded<association :employees is not loaded>,all matching
}
推荐的处理方式是什么?我显然想避免在测试中预加载关联,因为这样可以避免检查未在Profile.get_company!/1
中预加载它们的事实。
解决方法
恐怕您的断言也会失败,因为您正在处理不同的结构。您可以简单地遍历您的结构,并以%Ecto.Association.NotLoaded{}
作为值来删除字段,然后从您的第一个结构中删除那些字段,然后断言两者是相等的,就像这样:
def remove_not_loaded_associations(struct_with_assoc,struct_without_assoc) do
keys_to_remove =
struct_without_assoc
|> Map.from_struct()
|> Enum.filter(fn {_k,v} -> match?(%Ecto.Association.NotLoaded{},v))
|> Keyword.keys()
map1 =
struct_with_assoc
|> Map.from_struct()
|> Map.drop(keys_to_remove)
map2 =
struct_without_assoc
|> Map.from_struct()
|> Map.drop(keys_to_remove)
{map1,map2}
end
# ...
{map1,map2} = remove_not_loaded_associations(company,Profile.get_company!(company.id))
assert map1 == map2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。