Ecto 断言 #Ecto.Association.NotLoaded<association :xyz is not loaded>



我通常会检查我的测试是否返回预期结果,如下所示:

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>,
# more attributes, 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

相关内容

最新更新