Home > other >  Manually set FactoryBot's sequence value
Manually set FactoryBot's sequence value

Time:10-12

I use FactoryBot's sequence method to generate unique values, which work great in tests.

Example:

FactoryBot.define do
  factory :my_factory do
    sequence(:label) { |n| "Label #{n}" }
  end
end

However, if I try to generate records in my dev environment, I hit lots of errors because the sequence counter has reset. I would love to set it manually, something like set_sequence(123456), is anything like that possible?

CodePudding user response:

Sequence accepts a seed value parameter so something like this should work

FactoryBot.define do
  factory :my_factory do
    sequence(:label, 123456) { |n| "Label #{n}" }
  end
end

You could now set the start value in your configuration

# config/environments/production.rb
Rails.application.configure do
  config.x.factory_bot.sequence_seed_value = 1234
end

# config/environments/test.rb
Rails.application.configure do
  config.x.factory_bot.sequence_seed_value = 0
end


FactoryBot.define do
  factory :my_factory do
    sequence(:label, Rails.configuration.x.factory_bot.sequence_seed_value) { |n| "Label #{n}" }
  end
end

https://github.com/thoughtbot/factory_bot/blob/893eb67bbbde9d7f482852cc5133b4ab57e34b97/lib/factory_bot/sequence.rb#L13 https://github.com/thoughtbot/factory_bot/blob/893eb67bbbde9d7f482852cc5133b4ab57e34b97/spec/acceptance/sequence_spec.rb#L48 https://guides.rubyonrails.org/configuring.html#custom-configuration

  • Related