DEV Community

n350071๐Ÿ‡ฏ๐Ÿ‡ต
n350071๐Ÿ‡ฏ๐Ÿ‡ต

Posted on • Edited on

[RSpec] Factorybot trait, making a complex association data

๐Ÿค” 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


Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘ 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


Enter fullscreen mode Exit fullscreen mode

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') }


Enter fullscreen mode Exit fullscreen mode

๐Ÿ“š References


๐Ÿ”— Parent Note

Top comments (0)