Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom range with FactoryGirl sequence

In the old version something like this was possible (more examples):

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

Using this in the new FactoryGirl version will create an NoMethodError: undefined method 'next' for 0..10:Range.

In particular I have a model user which has multiple time_entries. I want to create default values. For simplicity each user should create n time entries. The entries are created like this:

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
like image 516
muma Avatar asked Aug 18 '14 12:08

muma


1 Answers

You have to pass an object that responds to next, e.g. an enumerator:

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

FactoryGirl.build(:user) #=> <#User @email="[email protected]">
FactoryGirl.build(:user) #=> <#User @email="[email protected]">
FactoryGirl.build(:user) #=> <#User @email="[email protected]">
# ...
FactoryGirl.build(:user) #=> <#User @email="[email protected]">
FactoryGirl.build(:user) #=> <#User @email="[email protected]">
# `cycle` will start over:
FactoryGirl.build(:user) #=> <#User @email="[email protected]">
like image 191
Stefan Avatar answered Sep 25 '22 12:09

Stefan