【问题标题】:Manually set FactoryBot's sequence value手动设置 FactoryBot 的序列值
【发布时间】:2021-10-11 00:20:15
【问题描述】:

我使用 FactoryBot 的 sequence 方法生成唯一值,这在测试中效果很好。

例子:

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

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

【问题讨论】:

    标签: ruby-on-rails factory-bot


    【解决方案1】:

    Sequence 接受种子值参数,所以这样的东西应该可以工作

    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

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多