Module: FactoryBurgers::Introspection

Defined in:
lib/factory_burgers/introspection.rb

Overview

Discover information about factories for a class, such as what associations are defined on that class that also have factories we can use

Class Method Summary collapse

Class Method Details

.association_factories(klass) ⇒ Object

Return a list of factories for a model instance’s associations



12
13
14
15
16
17
18
19
20
21
# File 'lib/factory_burgers/introspection.rb', line 12

def association_factories(klass)
  buildable_associations(klass).flat_map do |assoc|
    factories_for_class(assoc.klass).map do |factory|
      {
        association: assoc,
        factory: factory,
      }
    end
  end
end

.buildable_associations(klass) ⇒ Object



32
33
34
# File 'lib/factory_burgers/introspection.rb', line 32

def buildable_associations(klass)
  klass.reflect_on_all_associations.reject { |assoc| assoc.is_a?(ActiveRecord::Reflection::ThroughReflection) }
end

.factoriesObject



7
8
9
# File 'lib/factory_burgers/introspection.rb', line 7

def factories
  FactoryBurgers.factory_bot_adapter.factories.sort_by(&:name)
end

.factories_for_class(klass) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/factory_burgers/introspection.rb', line 23

def factories_for_class(klass)
  factories.select do |factory|
    factory.build_class.ancestors.include?(klass)
  rescue NameError
    # Some usages of factories include pseudo "abstract" factory parent classes that do not point to a real class
    false
  end
end