Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryBot get available traits for a factory

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?

like image 363
ibaralf Avatar asked Jul 27 '18 18:07

ibaralf


People also ask

What is traits in factory bot?

Traits allow you to group attributes together and then apply them to any factory.

What is Factorybot used for?

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.

What is Factorybot in Rspec?

Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl.

What is trait in Rspec?

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.


1 Answers

I believe what you want is the following:

FactoryBot.factories[:address].defined_traits.map(&:name)
#=> ["in_california", "in_new_york", "in_florida"]
like image 78
Kees Briggs Avatar answered Oct 06 '22 00:10

Kees Briggs