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. In such scenario rspec trait is good option. For few attributes we need different values and we want to use it at multiple places can be another reason to use it.
Without Trait:
FactoryGirl.define do
factory :package do
description FFaker::Lorem.sentence
end
end
package = create :package, is_set: true, set_value: 1
This code can be normalize as follow. It becomes more readable, reusable and clear with the help of traits.
With Trait:
FactoryGirl.define do
factory :package do
description FFaker::Lorem.sentence
trait :as_set do
is_set true
set_value 1
end
end
end
package = create :package, :as_set