🤔 Situation
class Author has_many :books has_many :title_covers, through: :book end class Book belongs_to :author has_many :title_covers end class TitleCover belongs_to :author belongs_to :book end
👍 Solution
preparing
FactoryBot.define do factory :author, class: Author do trait :with_a_book_and_title_covers do after(:build) do |author| author.books << FactoryBot.build(:book, :with_title_covers) end end end end FactoryBot.define do factory :book, class: Book do trait :with_title_covers do after(:build) do |book| book.title_covers = FactoryBot.build_list(:title_cover, 2) end end end end
Note1: <<
for build
, =
for build_list
to make the relations.
Note2: if you use after(:create)
, don't forget to .save
.
🎉 Use it
You can easily make an array of author which has a book that has two book covers, and the author name is n350071
.
let(:author){ create(:author, :with_a_book_and_title_covers, name: 'n350071') }
Top comments (0)