Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 736
swapab Avatar asked Jan 10 '16 05:01

swapab


1 Answers

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.

like image 161
Dave Schweisguth Avatar answered Sep 29 '22 16:09

Dave Schweisguth