Factory Girl - HABTM的可变数量的关联对象

时间:2011-09-01 09:44:26

标签: ruby unit-testing tdd factory-bot

如果我有2个型号 - 例如商店和品牌,我想模仿3至10个品牌之间的商店,使用工厂女孩这样做的好方法是什么?

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}")
    end
  }
end

这显然不是这样做的方法,但应该知道我想要实现的目标!

1 个答案:

答案 0 :(得分:3)

我现在无法测试它,但这应该有效:

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

或者这个:

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