thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.91k stars 2.6k forks source link

has_many relations #1645

Open mike-burns opened 4 months ago

mike-burns commented 4 months ago

I'd like to be able to clearly, safely, and idiomatically create an object and its many relations. For example:

new_author = create(:author)
distinguished_author = create(:author, with_article_count: 3)

assert_equal new_author.articles.count, 0
assert_equal distinguished_author.articles.count, 3

The above can currently be done using a transient property and some hooks, but it's kinda kludgy and hard to get right. Let's make this somewhat common case easier and less error prone.

It could look like this:

FactoryBot.define do
  factory :author do
    association(:article, relation: :has_many)
  end
end

Or it could allow overrides:

FactoryBot.define do
  factory :author do
    association(:unique_article, relation: :has_many) do |user, offset|
      title { "How to win, part #{offset + 1}" } # sets the title for the article
    end
  end
end