elixir - 使用 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" }
}
我试图避免:
在我左边的记录上使用
Repo.preload
,因为有时有很多依赖项单独测试每个属性
提前感谢您的帮助
解决方案
我通过定义一个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
推荐阅读
- python - 过滤,返回输入列表中包含指定键的所有字典的列表:值对
- go - Flutter,在 prebuild GO .so 库上使用 DynamicLibrary.open() 而无需编写 Native Code(Java/Swift)
- php - Laravel 登录后立即注销用户
- r - 如何基于多列创建因子以进行绘图
- postgresql - PostgreSQL 9.3 在事务中空闲
- node.js - 请求状态码得到 404 但在邮递员中工作 - 节点
- mysql - 创建数据库查询 Spring Boot JPA?
- ios - Ionic3/iOS:删除“指针事件:无”不会重新启用滚动
- javascript - 更改 facebook HTML & CSS 的内置登录按钮的样式
- specflow - 为什么有人想在 Specflow 中使用不同的测试运行器?