首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >loaded>断言#Ecto.Association.NotLoaded<association :xyz不是Ecto

loaded>断言#Ecto.Association.NotLoaded<association :xyz不是Ecto
EN

Stack Overflow用户
提问于 2020-10-08 16:35:20
回答 1查看 463关注 0票数 0

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

代码语言:javascript
复制
company = company_fixture() # inserts a company in the database with default attributes
assert Profile.get_company!(company.id) == company

但这失败了

代码语言:javascript
复制
     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中预加载的事实。

EN

回答 1

Stack Overflow用户

发布于 2020-10-09 01:55:04

我担心您的断言也会失败,因为您正在处理不同的结构。您可以简单地迭代您的结构并删除值为%Ecto.Association.NotLoaded{}的字段,然后也从第一个结构中删除这些字段,然后断言两者相等,如下所示:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64258775

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档