具有FactoryGirl序列的自定义范围

时间:2014-08-18 12:27:48

标签: ruby-on-rails factory-bot

在旧版本中,这样的事情是可能的(more examples):

Factory.sequence(:email, 50..60) do |n|
  "user_#{n}@example.com"
end

在新的FactoryGirl版本中使用此功能将创建NoMethodError: undefined method 'next' for 0..10:Range

特别是我的模型user有多个time_entries。我想创建默认值。为简单起见,每个用户都应创建n个时间条目。条目创建如下:

FactoryGirl.define do
  factory :time_entry do
    start_time { generate(:time_entry_begin) }
    end_time { generate(:time_entry_end) }
  end
end

FactoryGirl.define do
  sequence(:time_entry_begin, 0..10) do |n|
    DateTime.now - n.hours
  end
end

FactoryGirl.define do 
  sequence(:time_entry_end, 0..10) do |n|
    DateTime.now - n.hours + (1 + n).minutes
  end
end

1 个答案:

答案 0 :(得分:14)

您必须传递响应next的对象,例如一个普查员:

FactoryGirl.define do
  factory :user do
    sequence(:email, (50..60).cycle) { |n| "user_#{n}@example.com" }
  end
end

FactoryGirl.build(:user) #=> <#User @email="user_50@example.com">
FactoryGirl.build(:user) #=> <#User @email="user_51@example.com">
FactoryGirl.build(:user) #=> <#User @email="user_52@example.com">
# ...
FactoryGirl.build(:user) #=> <#User @email="user_59@example.com">
FactoryGirl.build(:user) #=> <#User @email="user_60@example.com">
# `cycle` will start over:
FactoryGirl.build(:user) #=> <#User @email="user_50@example.com">