如何在工厂中跳过after_build回调?

时间:2013-02-20 13:52:55

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

创建工厂时我遇到了问题。我有一家工厂:

Factory.define :job do |j|
  j.association :service_partner, :factory => :service_partner
  j.price_per_task 1.to_money
  end
  j.after_build{|j| j.project.service_partner_ids = [j.service_partner.id] unless j.service_partner.nil?}
end

如何在创建工厂时跳过after_build?

1 个答案:

答案 0 :(得分:1)

如果您只想让after_build回调偶尔运行,最好的办法是定义一个嵌套工厂:

Factory.define :job do |j|
  j.association :service_partner, :factory => :service_partner
  j.price_per_task 1.to_money
  end
  factory :job_with_additional_setup do
    j.after_build{|j| j.project.service_partner_ids = [j.service_partner.id] unless j.service_partner.nil?}
  end
end

然后,您可以通过执行FactoryGirl.create(:job)或使用after_build创建正常作业:FactoryGirl.create(:job_with_additional_setup)