有参数的工厂

Factory with arguments

我有简单的工厂:

FactoryGirl.define do
  factory :event_with_tags do
    name 'event-name'
    start_date '2016-03-16'
    start_time '11:34'
    tags = %w(foo bar)
    after(:create) do |event|
      tags.each do |tag|
        event.tags << create(:tag, name: tag)
      end
    end
  end
end

是否有可能以这样的方式创建工厂,我可以像这样或类似的方式使用它?:

FactoryGirl.create(:event_with_tags, tags: 'foo bar qux')

是的,这是可能的。您应该使用 Transient Attributes 即声明 tags 为临时属性。