FactoryBot 不触发特征回调

FactoryBot not trigger callback in trait

我有一个工厂有一个特点。我在创建后添加了回调,但未触发回调。我知道这一点是因为我无法窥探。我正在使用 FactoryBot 5 和 Rails 4.2.11

factory :document do
  trait :signed do
    after :create do |doc|
      binding.pry
      doc.signatures << create(:signatures)
    end
  end
end

我的测试

  let!(:document) { build(:document, :signed) }

  %w[...].each do |field|
    it "filters by document.#{field}" do
      ...
      co.contents << create(:content, documents: [document])
      ... 
   end
  end

也尝试过使用 transient 而不是 trait 但它不起作用

transient do
  signed { false }
end

after :create do |doc, options|
  binding.pry
  doc.signatures << create(:signature) if options.signed
end


let!(:document) { build(:document, signed: true) }

after(:create) 回调不会被调用,因为您没有创建 document with FactoryBot.create.

下面的代码应该可以工作。

let!(:document) { create(:document, :signed) }

有关详细信息,请阅读 FactoryBot callback docs