Search code examples
ruby-on-railsrspecfactory-bot

How to unset a property in a FactoryBot trait?


In my model, I have a property foo that have a default value.

I want to write a test related with the default value of foo, but my FactoryBot is setting its as nil (and overriding the default value).

If I remove foo from the factory bot it will break some other tests. So I would like to use something like a trait to create a case where foo is not net, but I didn't find any way to unset the property.

Is there some way to unset a property in FactoryBot?

FactoryBot.define do
  factory :my_model do
    foo { 'abc' }
    bar { 'abc' }

    trait(:foo_not_set) do
      # magic to unset foo
    end
  end
end

Solution

  • You can play around with virtual attributes with transient block:

    FactoryBot.define do
      factory :my_model do
        bar { 'abc' }
    
        transient do
          default_values true
        end
    
        before(:create) do |my_model, evaluator|
          if evaluator.default_values?
            foo { 'abc' }
          end
        end
    
        trait(:foo_not_set) do
          transient do
            default_values { false }
          end
        end
      end
    end