Has_and_belongs_to_many associations in factory_girl 4.1

I am new to factory_girl and trying to figure out how to efficiently generate a factory for the following models:

class Company < ActiveRecord::Base has_and_belongs_to_many :tags end class Tags < ActiveRecord::Base has_and_belongs_to_many :companies validates :type , :inclusion => { :in => %w(market location) } end 

I reviewed previous answers to StackOverflow (including this one ), however most of them are outdated and / or do not have the correct answer to the question. Is there anyone who can help identify the factories for these two objects with Factorygirl?

Update

Here is what I have found so far

 FactoryGirl.define do factory :tag do id 448 trait :market do type "market" end trait :location do type "location" end name "software" end factory :company do id 1234 name "Apple Inc." factory :company_with_tags do #setting the default # of tags for companies ignore do tag_count 2 end after(:create) do |company , evaluator| FactoryGirl.create_list(:tag , evaluator.tag_count , company: company) end end end end 
+4
source share
1 answer

I think the problem is that the association name is incorrect. A Tag has many companies, and not one, therefore:

 after(:create) do |company , evaluator| FactoryGirl.create_list(:tag , evaluator.tag_count , companies: [company]) end 

As a side note, you want to avoid using type as the column name if you are not trying to establish polymorphic relationships.

+2
source

Source: https://habr.com/ru/post/1442195/


All Articles