Consider the following set of relationships:
User —> Orders ----> Items
A user has many Orders which may have many items. I am writing an integration test where I first insert a user using a factory, then create two orders and then create multiple items for each of those orders. My current code look like below:
%{id: user_id} = insert(:user)
%{
name: name,
id: id,
orders: [
%{
:date first_order_date,
:value: first_value,
:id: first_order_id
},
%{
:date second_order_date,
:value: first_value,
:id: second_order_id
}
| _
]
} =
insert(:user_orders,
orders: [
%{date: ~D[2020-01-01], value: 200},
%{date: ~D[2019-01-01], value: 300}
]
)
%{value: first_order_items} =
insert(
:order_items,
%{
user_id: user_id,
order_id: first_order_id,
....
}
)
%{value: second_order_items} =
insert(
:order_items,
%{
order_items: user_id,
order_id: second_order_id,
....
}
)
What is the most idiomatic and concise way of writing the above - the last two insert statements in particular? Can the nested relationships be inserted in a single invocation of insert?