如何获取为特定模型 class 定义的所有 factory_girl 工厂?

How to get all factory_girl factories defined for a particular model class?

我在 <Rails-root>/spec/factories/models.rb 中定义了一个工厂:

FactoryGirl.define do
  factory :model do
    id 1
    association :organization, factory: :aureso
    name "Default Model"

    factory :serie_1 do
      id 2
      name 'serie_1'
    end

    factory :serie_2 do
      id 3
      name 'serie_2'
    end

    factory :serie_3 do
      id 4
      name 'serie_3'
    end
  end
end

我想获取为 Class Model 定义的所有工厂。

我可以使用 FactoryGirl.factories 获得所有 class 的出厂定义,是的,我可以使用 map/reduce 实现上述目标。但我想知道是否有任何辅助方法来获取模型的所有定义 class.

the source可以看出,factory_girl(4.5.0)当前版本的FactoryGirlclass没有方便的列出方式创建给定 class.

实例的工厂

这不是一个非常令人兴奋的答案,所以让我们以不方便的方式来做吧! FactoryGirl.factoriesreturns一个FactoryGirl::Registry, which again doesn't have a convenient way to list factories but does have an @items hash whose keys are factory names and whose values are instances of FactoryGirl::Factory。给定 Factory 构建其实例的 class 由 Factory#build_class 返回。所以我们可以列出构建给定 class 和

实例的工厂
FactoryGirl.
  factories.
  instance_variable_get('@items').
  select { |name, factory| factory.build_class == SomeClass }.
  keys

既然依赖内部结构,以后肯定会坏掉的。