如何从FactoryGirl工厂返回子类?

时间:2016-12-08 14:54:40

标签: ruby-on-rails ruby factory-bot

我有Fruit个,可以是ApplesOranges。我从不想实际实例化Fruit类。我可以在像这样的工厂中定义子类:

# factories.rb
factory :fruit do
  juiciness 3
  ripeness 4

  factory :apple, class: Apple do
    color 'red'
  end

  factory :orange, class: Orange do
    color 'orange'
  end
end

我希望FactoryGirl.create_list :fruit, 10返回AppleOrange个对象的列表,而不是Fruit个对象。当我致电Apple时,如何让FactoryGirl随机返回OrangeFactoryGirl.create :fruit

1 个答案:

答案 0 :(得分:1)

你不能在方法中这样做吗?

def create_fruit_list(count=1)
  result = []
  count.times do 
    result << create([:apple, :orange].sample)
  end
  result
end