How to use preloads when testing associations

Does anyone have a good example of how to use preloads while testing? The new generators create test files that need a little TLC after you add associations. I haven’t found a good example yet.

1 Like

Assuming you have a User schema with has_one UserProfile.

setup do
  user = Repo.insert!(%User{})
  user_profile = Repo.insert!(%UserProfile{user: user})
  {:ok, user: user}
end

test "association is valid", %{user: user} do
  user = Repo.preload(user, [:user_profile])
  
  assert !is_nil(user.user_profile)
end
1 Like