FactoryBot get available traits for a factory
Asked Answered
S

1

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?

Soapbark answered 27/7, 2018 at 18:50 Comment(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. @jvillianSoapbark
@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'Woad
@Woad - 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.Bey
@Soapbark 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_traitsWoad
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.Soapbark
H
11

I believe what you want is the following:

FactoryBot.factories[:address].defined_traits.map(&:name)
#=> ["in_california", "in_new_york", "in_florida"]
Heritable answered 4/12, 2018 at 20:14 Comment(1)
That's the one. Thanks. I edited your answer and added .map(&:name) and the returned value, to complete your example.Kieserite

© 2022 - 2024 — McMap. All rights reserved.