根据在同一工厂的另一个字段中设置的数字创建工厂字段值

Create a factory field value based on a number set in another field in the same factory

我有一个 table,其中 data_value 是基于 option_id 设置的。例如,

 option_id: 1 , data_value: `date value`
 option_id: 2, data_value: number
 option_id: 3, data_value: text


  FactoryBot.define do
       factory  :test do
           sequence(:option_id, (1..3).cycle) { |n| n }
           data_value {??} 
        end 
    end

如何让 FactoryBot 根据 option_id 生成 data_value?

您可以在块中使用 after(:build) callback which will let you do things to the generated object after it is created but before it's returned. Depending on how your class actually works, you may not want to store option_id directly on the class. In that case, you can use the values object 来读取传递给工厂的原始值。

require 'factory_bot'
require 'ostruct'

FactoryBot.define do
  factory :test, class: OpenStruct do
    sequence(:option_id, (1..3).cycle) { |n| n }

    after(:build) do |o, values|
      o.data_value = case values.option_id
                     when 1
                       Time.now
                     when 2
                       5
                     when 3
                       'hello world'
                     end
    end
  end 
end

puts(FactoryBot.build(:test))
puts(FactoryBot.build(:test))
puts(FactoryBot.build(:test))

最后三行将输出如下内容:

#<OpenStruct option_id=1, data_value=2019-09-24 00:44:01 +0000>
#<OpenStruct option_id=2, data_value=5>
#<OpenStruct option_id=3, data_value="hello world">