FactoryBot 未在创建回调后创建关联模型列表

FactoryBot is not creating the associated models list in the after create callback

我有两个工厂如下:

FactoryBot.define do
  factory :proofread_document do

    factory :proofread_document_with_paragraphs do
      after(:create) {|instance| create_list(:paragraph, 5, proofread_document: instance) }
    end
  end
end

    FactoryBot.define do
      factory :paragraph do
        level { 1 }
        association :proofread_document
    end
end

在我的 RSpec 测试中:

  describe '#number_of_paragraphs_for' do

    let(:proofread_document) { create(:proofread_document_with_paragraphs)}

    it 'returns the number of paragraphs for the given level' do
      expect(proofread_document.number_of_paragraphs_for("level_1")).to eq(1)
    end
  end

测试失败,因为没有段落:

proofead_document.paragraphs
=> []

为什么没有创建关联的段落对象?

关联不会神奇地重新加载到现有实例上。这不是因为 FactoryBot,而是因为 ActiveRecord 本身。

# example with activerecord:

class Foo
  has_many :bars
end

class Bar
  belongs_to :foo
end

foo = Foo.first
foo.bars
# => []
3.times { Bar.create(foo: foo) }
foo.bars
# => []
foo.reload.bars
# => [<#Bar ...>, <#Bar ...>, <#Bar ...>]

所以你只需要重新加载记录(或只是关联)

after(:create) do |inst|
  create_list(...)
  inst.paragraphs.reload
  # or inst.reload
end

我发现了问题。

在我的段落模型中,我放置了一个默认范围,如下所示:

default_scope :minimum_word_count,  ->{ where(proofread_word_count: MINIMUM_LEVEL_DATA_WORD_COUNT..Float::INFINITY)}

这导致了一些问题,因为我在测试中保存的段落的字数对于在此范围内定义的参数来说太少了。

@P.Boro 和@rewritten 帮助我重新检查我的模型和示波器。