Disabling a FactoryGirl association within a trait

瘦欲@ 提交于 2019-12-06 12:04:08

An association in factory_girl is just an attribute like any other. Using association :bar sets the bar attribute, so you can disable it by overriding it with nil:

FactoryGirl.define do
  factory :foo do
    attribute "value"
    association :bar

    trait :one do
      # This has the bar association
    end

    trait :two do
      bar nil
    end
  end
end

I tried @Joe Ferris' answer but appears it does not work anymore in factory_bot 5.0.0. I found this related question that referred to the strategy: :null flag that can be passed to the association like:

FactoryGirl.define do
  factory :foo do
    attribute "value"
    association :bar

    trait :one do
      # This has the bar association
    end

    trait :two do
      association :bar, strategy: :null
    end
  end
end

It seems to do the trick now.

Source code looks like it just stops any callbacks like create or build so renders the association to nothing.

module FactoryBot
  module Strategy
    class Null
      def association(runner); end

      def result(evaluation); end
    end
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!