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

1

9

I have a factory defined in <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

I want to get all the factories defined for Class Model.

I can get factory definitions for all classes with FactoryGirl.factories, and yes, I can achieve the above using map/reduce. But I want to know if there is any helper method to get all definitions for a model class.

Exemplification answered 10/1, 2016 at 5:4 Comment(3)
i really don't understand what are you talking about. Factory is basically a object representing a certain model. ActiveModel Model is a class that includes validations and other plain ruby things, and it is part of ActiveRecord::Base class, from which model inherits. If you are speaking about some shared logic between all factories, you can use traits.Expiratory
you should create different factories for different models. remove id attribute, because id creates by database.Caliginous
I am using fixture-builder (github.com/rdy/fixture_builder) and I want id to be self defined which is useful for sequencing. That's not causing me any problem. I just wanted to know is there a way to get all factories referencing to a model class in this case :model(class name Model).Exemplification
R
8

As one can see from the source, the FactoryGirl class in the current version of factory_girl (4.5.0) does not have a convenient way to list the factories that create instances of a given class.

That's not a very exciting answer, so let's do it the inconvenient way! FactoryGirl.factories returns a 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. The class which a given Factory builds instances of is returned by Factory#build_class. So we can list the factories that build instances of a given class with

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

Since that relies on internals, it's sure to break in the future.

Richard answered 16/1, 2016 at 18:53 Comment(3)
Nice.Thanks for @items. Can you locate me to the source code(or doc.) where the instance variable is mentioned ?Exemplification
I did! Follow the link to FactoryGirl::Registry.Richard
Since FactoryBot::Registry is an Enumerable of Factories, you can do this without accessing @items (although it still uses undocumented APIs): FactoryBot.factories.select { |f| f.build_class == SomeClass }.map(&:name)Intonate

© 2022 - 2024 — McMap. All rights reserved.