Not sure about DataMapper
(and how that fits in/if it's included in the factory definition) but for the associations, do this:
FactoryGirl.define do
factory :C do |c|
...
c.association :a
c.association :b
end
end
Question
I want to specify following type of associations through FactoryGirl. I have three models A, B and C where model of C which is in DataMapper is as follows:
Class C do
include DataMapper::Resource
belongs_to :A, :key=>true
belongs_to :B, :key=>true
end
I don't know how to specify this in FactoryGirl i.e. what I mean is I want to write like this:
factory :c do |c|
<To be Filled>
end
Please help.
La solution
Not sure about DataMapper
(and how that fits in/if it's included in the factory definition) but for the associations, do this:
FactoryGirl.define do
factory :C do |c|
...
c.association :a
c.association :b
end
end
Autres conseils
License belongs to LicenseTemplate
FactoryGirl.define do
factory :license do
start_date { Time.now}
end_date { Time.now + 30.days }
factory :license_with_template do
association :license_template, factory: :license_template
end
after(:build) do |doc|
if doc.license_template
doc.agents_count = doc.license_template.agents
doc.requests = doc.license_template.requests
end
end
end
end
the above code gives me two factories 'license' and 'license_with_template'. the after 'build' block initializes the values which need to be initialized before the object is saved.
FactoryGirl.define do
factory :c do |f|
f.a
f.b
end
end
if you create the factories for both a
and b
and you make sure that the names of the factories are the same as those of the model,that is all you need to specify the association. FactoryGirl will create both a
and b
every time you do: FactoryGirl.create(:c)
. The association should be specified on one side only, preferably the belongs to side.