0

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

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

4

1 回答 1

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
于 2020-10-08T17:55:04.153 回答