Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a table where the data_value is set based on option_id. Example,

 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

How do I make FactoryBot generate data_value based on the option_id?

like image 482
NewUser123 Avatar asked Oct 31 '25 12:10

NewUser123


1 Answers

You can make that work with an 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 in the block to read the original value passed into the factory.

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))

Those last three lines will output something like:

#<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">
like image 188
supersam654 Avatar answered Nov 03 '25 15:11

supersam654



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!