Rails FactoryGirl Factory具有可选的模型关联

时间:2016-03-05 00:43:36

标签: ruby-on-rails factory-bot

根据rails 4 model association left join validate id我必须更新我的工厂。我正在尝试创建一个可以创建优惠券的条件,但是只有在执行时才分配作业ID,即:

FactoryGirl.define do
  factory :coupon do
    code { rand(25**25) }
    percent_discount { rand(100**1) }
    start_at { Time.now }
    end_at { 30.day.from_now }

    trait :executed do |c|
      job
      c.executed_at { Time.now }
    end
  end
end

enter image description here

2 个答案:

答案 0 :(得分:0)

您似乎应该从优惠券模型中删除validates :job, presence: truevalidates :job_id, presence: true之类的内容

答案 1 :(得分:0)

您可以在工厂中使用回调。这是一个例子:

FactoryGirl.define do
  factory :coupon do
    code { rand(25**25) }
    percent_discount { rand(100**1) }
    start_at { Time.now }
    end_at { 30.day.from_now }

    after(:create) do |c|
      #do job related stuff
    end
  end
end

查看其文档以获取更多信息: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#callbacks

更新

根据您的上一次评论,我认为特质不会有用。这是我理解的create coupon > do some process > execute coupon > assign job。因此,在创建优惠券后,我认为优惠券有一些延迟/处理逻辑。因此,当您在此时执行优惠券时,您需要创建工作对象并与该优惠券关联。我相信以下内容适合该流程:

FactoryGirl.define do
  factory :coupon do
    code { rand(25**25) }
    percent_discount { rand(100**1) }
    start_at { Time.now }
    end_at { 30.day.from_now }

    #This trait is used in case, 
    #if you want job to be assigned to coupon
    #for example create(:coupon,:executed)
    trait :executed do |c|
      association :job, factory: [:job] 
      c.executed_at { Time.now }
    end

  end
end

#In Test Case
@coupon = create(:coupon)
#have some test for coupon before execution
#now executing coupon
@coupon.update_attributes(job_id: create(:job), executed_at: Time.now)