Factory Girl - variable number of associated objects for HABTM
If I have 2 models - eg. Shop and Brand and i want to model the shop having between say, 3 - 10 brands, what is a good way to do that using factory girl?
factory :brand do |b|
b.name "Hip Brand"
b.url { "http://#{name}.com" }
end
factory :shop do |s|
name "Cool Shop"
after_create {
count = 0
(5..10).to_a.sample.times do
count += 1
Factory(:brand, :shops => s, :name => "brand #{count}")
开发者_如何学C end
}
end
This is obviously not the way to do it, but should give an idea of what I'd like to achieve!
I can't test it at the moment, but this should work:
Factory.define :brand, :class => Brand do |b|
b.name "Hip Brand"
b.url { "http://#{name}.com" }
end
Factory.define :shop, :class => Shop do |s|
s.name "Cool Shop"
s.brands {
count = 0
Array(5..10).sample.times.map do
Factory.create(:brand, :name => "Brand #{count += 1}")
end
}
end
Or this:
Factory.define :shop, :class => Shop do |s|
s.name "Cool Shop"
s.brand_ids {
count = 0
Array(5..10).sample.times.map do
Factory.create(:brand, :name => "Brand #{count += 1}")[:id]
end
}
end
精彩评论