Custom range with FactoryGirl sequence
Asked Answered
H

1

7

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
Hairworm answered 18/8, 2014 at 12:27 Comment(0)
I
16

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]">
Intrust answered 18/8, 2014 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.