开发者

Factory Girl - variable number of associated objects for HABTM

开发者 https://www.devze.com 2023-04-01 14:56 出处:网络
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?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号