9

Is there a FactoryBot method or some way to get available traits for a factory?

Ex:

FactoryBot.define do
  factory :address, class: Address do
    trait :in_california do
      state 'CA'
    end

    trait :in_new_york do
      state 'NY'
    end

    trait :in_florida do
      state 'FL'
    end
end

I want to be able to get the traits programatically, something like FactoryBot.get_traits (:address) and it would return an array of the traits defined for that factory, in this case that would be

["in_california", "in_new_york", "in_florida"]

Does that make it clearer?

5
  • I did a search and could not find anything related. I was wondering if there was a way get the traits given a factory. I am using an interactive tool (thor gem) to allow users to select which traits to give a factory, that's why I'm asking this. @jvillian
    – ibaralf
    Commented Jul 27, 2018 at 20:49
  • @jvillian that's not what trait is. I.e. factory ':user' can have many traits which run some callbacks, etc. I.e. ':user_with_payments' can do some other stuff. attributes_for(:my_factory).keys will return only the keys from the hash of attributes defined in the factory ':user'
    – jedi
    Commented Jul 27, 2018 at 21:06
  • @jedi - My apologies, I haven't used traits before on my factories. As such, I was down the entirely wrong path. I'll delete my answer and comments as I haven't added anything helpful.
    – jvillian
    Commented Jul 27, 2018 at 21:22
  • 2
    @ibaralf try FactoryBot.factory_by_name(:your_factory).defined_traits. Try also FactoryBot.factories or FactoryBot.traits. You can also take a look at FactoryBot.configuration.factories[:your_factory].defined_traits
    – jedi
    Commented Jul 27, 2018 at 21:38
  • FactoryBot.configuration.factories[:your_factory].defined_traits . This seems to give me the Set of traits. Thanks, didn't see this in the actual documentation or was very difficult to search.
    – ibaralf
    Commented Jul 27, 2018 at 21:53

1 Answer 1

11

I believe what you want is the following:

FactoryBot.factories[:address].defined_traits.map(&:name)
#=> ["in_california", "in_new_york", "in_florida"]
1
  • 1
    That's the one. Thanks. I edited your answer and added .map(&:name) and the returned value, to complete your example. Commented Nov 17, 2021 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.