FactoryGirl带有局部变量

时间:2011-11-15 11:33:08

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

我正在尝试在将来的某个随机时间创建一个time_slot:

FactoryGirl.define do
  factory :time_slot do
    week_num = (rand(10) +1)
    day_num = (1+rand(30))
    hour_num = (1+rand(12))
    future_date = week_num.weeks.from_now
    my_time = Date.local(future_date.year,future_date.month,day_num, hour_num)
    sold_out false
    fitness_camp
    start_time {my_time}
    end_time {my_time + 8.weeks}

但这导致undefined method + for #<FactoryGirl::Declaration::Static

我知道这可以在一条巨大的线上运作,但必须有一个干净的方法来做到这一点。将局部变量与属性混合是令人困惑的,因此最好将此函数放在其他位置并通过覆盖默认日期来生成Factory吗?

谢谢,

1 个答案:

答案 0 :(得分:3)

使用Random.rand()代替rand()

 FactoryGirl.define do
   factory :time_slot do
     week_num = (Random.rand(10) +1)
     day_num = (1+Random.rand(30))
     hour_num = (1+Random.rand(12))
     future_date = week_num.weeks.from_now
     my_time = Date.local(future_date.year,future_date.month,day_num, hour_num)
     sold_out false
     fitness_camp
     start_time {my_time}
     end_time {my_time + 8.weeks}