首页 > 解决方案 > 使用 ExMachina 插入后是否可以不加载关联?

问题描述

我正在使用ex_machina为我的单元测试创​​建夹具。

我正在使用 ExMachina 将一些记录保存到数据库中,insert(:comment)但我的断言是错误的,因为 ExMachina 总是加载关系,而当我使用 Ecto 获取而不调用Repo.preload.

假设我有 2 家工厂comment,并且user

def user_factory do
  %User{
    name: "some name"
  }
end

def comment_factory do
  %Comment{
    content: "some content",
    user: build(:user)
  }
end

当我测试时

  test "should retrieve last comment" do
    comment = fixture(:comment)
    assert Comment.get_last_comment() == comment
  end

断言如果失败,因为在左边我有

%Comment{
    ...,
    content: "some content",
    user: #Ecto.Association.NotLoaded<association :user is not loaded>
}

在右边

%Comment{
    ...,
    content: "some content",
    user: %User{ name: "some name" }
}

我试图避免:

提前感谢您的帮助

标签: elixirex-unit

解决方案


我通过定义一个equal_records函数来解决这个问题,该函数test/support/data_case.ex只比较结构的类型和记录的 id:

def equal_records(%{__struct__: t1, id: id1}, %{__struct__: t2, id: id2}) do
  t1 == t2 and id1 == id2
end

def equal_records(_, _), do: false

用法:

test "should retrieve last comment" do
  comment = fixture(:comment)
  assert equal_records(Comment.get_last_comment(), comment)
end

要同时测试记录列表,请添加以下函数:

def equal_records([], []), do: true
def equal_records([h1 | t1], [h2 | t2]) do
  equal_records(h1, h2) and equal_records(t1, t2)
end

推荐阅读