手动设置 FactoryBot 的序列值

Manually set FactoryBot's sequence value

我使用 FactoryBot 的 sequence 方法生成唯一值,这在测试中非常有效。

示例:

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

但是,如果我尝试在我的开发环境中生成记录,我会遇到很多错误,因为序列计数器已重置。我很想手动设置它,比如 set_sequence(123456),这样的事情可行吗?

序列接受一个种子值参数,所以像这样的东西应该可以工作

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

您现在可以在配置中设置起始值

# 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