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?
Traits allow you to group attributes together and then apply them to any factory.
Factory Bot is often used in testing Ruby on Rails applications; where it replaces Rails' built-in fixture mechanism. Rails' default setup uses a pre-populated database as test fixtures, which are global for the complete test suite.
Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl.
Rspec has great feature and that is trait. In rspec we create factory for each class which provides the simplest set of attributes necessary to create an instance of that class. Many times we need some attributes which we do not want to add in original factory and at the same time we do not want to repeat it.
I believe what you want is the following:
FactoryBot.factories[:address].defined_traits.map(&:name)
#=> ["in_california", "in_new_york", "in_florida"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With