Home > other >  factory_bot add two or more associations in create method
factory_bot add two or more associations in create method

Time:08-19

I have a user model with many accounts.

In my test I want to use factory_bot to create user with two or more accounts

Currently I can do it by making a user and two accounts separately via factory_bot, then adding the accounts after like this:

@user = create(:user)

#Create two Accounts
@account_1 = create(:account)
@account_2 = create(:account)


#Add accounts to User
@user.accounts << @account_1
@user.accounts << @account_2

I'd ideally like to set it up like this or similar:

@user = create(:user, accounts: [@account_1, @account_2])

I need access to account for other models set up later.

CodePudding user response:

You can do this with FactoryBot's transient_attributes, so set up your factory like this:

FactoryBot.define do
  factory :user do
    firstName { Faker::Name.first_name }
    lastName { Faker::Name.last_name  }
    # etc

    transient do
      accounts {[]}
    end

    after(:create) do |user, evaluator|
      user.accounts << evaluator.accounts
    end
  end
end

and you can create the user by:

FactoryBot.create(:user, accounts: [FactoryBot.create(:account), FactoryBot.create(:account)])

CodePudding user response:

You can use accounts_count transient attribute

FactoryBot.define do
  factory :account do
    # some account attributes

    user
  end

  factory :user do
    # some user attributes

    factory :user_with_accounts do
      transient do
        accounts_count { 2 }
      end

      accounts do
        Array.new(accounts_count) { association(:account) }
      end
    end
  end
end

@user = create(:user_with_accounts)
@account1, @account2 = @user.accounts

create(:user_with_accounts, accounts_count: 5).accounts.size # 5
build(:user_with_accounts, accounts_count: 5).accounts.size # 5
build_stubbed(:user_with_accounts, accounts_count: 5).accounts.size # 5
  • Related