Reputation: 7379
I'm new to factory_girl and trying to figure out how to effectively 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've taken a look at previous answers on StackOverflow (including this one), however most of them are outdated and/or don't have a proper answer to the question. Is there anybody out there that can help define factories for these two objects with Factorygirl?
Update
Here's what I've come up wtih 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
Upvotes: 4
Views: 1829
Reputation: 47548
I think the problem is that the association name is specified incorrectly. A Tag
has many companies, not one, so:
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 a column name, unless you are trying to set up a polymorphic relationship.
Upvotes: 2