本文介绍了带有可选模型关联的Rails FactoryGirl Factory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照 rails 4模型关联左联接验证id 我不得不更新我的工厂.我正在尝试创建一个条件,在该条件中可以创建优惠券,但是仅在执行时才分配一个工作ID,即:

In accordance with rails 4 model association left join validate id I had to update my factories. I am trying to create a condition where a coupon can be created, but has a job id only assigned when it is executed i.e. :

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

推荐答案

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

You can use callbacks in factory. Here is an example of it :

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

Checkout its documentation for more information :https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#callbacks

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

Based on your last comment, I believe trait will not be useful. Here is something I understand create coupon > do some process > execute coupon > assign job. So after creating coupon I think there is some delay / process logic of coupon. So when you execute coupon at this time you need to create object of job and associate with that coupon. I believe following would be suitable for that flow :

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)

这篇关于带有可选模型关联的Rails FactoryGirl Factory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 10:52