[ FactoryGirl ] trait

Traits : group attributes together and then apply them to any factory

Callback Example

  • after(:build) – called after a factory is built (via FactoryBot.build, FactoryBot.create)
  • before(:create) – called before a factory is saved (via FactoryBot.create)
  • after(:create) – called after a factory is saved (via FactoryBot.create)
  • after(:stub) – called after a factory is stubbed (via FactoryBot.build_stubbed)

spec/factories/users.rb

FactoryGirl.define do
  ...
  trait :with_items do
    ignore do
      number_of_items 3
    end
   after(:create) do |user, evaluator|
     (0..evaluator.number_of_items-1).each do |number|
       create(:user_item, text: "item_#{number + 1}", user_id: user.id, position: number)
     end
   end
end

Usage

let(:user_1) { 

create(:user, :with_items, number_of_items: 7) 

}

ref : https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#traits

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s