sethi
sethi

Reputation: 1889

Rspec with let and inter dependent models

I am creating some dependencies models with let for Rspec.

The issue is I have to lot of objects in a particular order. Here is my code please let me know if there is a better way to do things

let(:users) do
 FactoryGirl.create_list(:users, 10)
end 

let(:contacts) do 
  contacts = []
  users.each do |user|
   contacts << FactoryGirl.create_list(:contact, 3, user: user.id)
  end
  contacts 
end

I dont like the way contacts are created and would like to know if there is a better way to do it with let,FactoryGirl in rspec.

Upvotes: 1

Views: 272

Answers (1)

Yury Lebedev
Yury Lebedev

Reputation: 4015

You could create a trait :with_users, which will build the users already with contacts:

FactoryGirl.define do
  factory :user do
    name "John Doe"

    factory :with_contacts do
      transient do
        contacts_count 3
      end

      after(:create) do |user, evaluator|
        create_list(:contact, evaluator.contacts_count, user: user)
      end
    end
  end
end

And then in your test:

let(:users) do
 FactoryGirl.create_list(:users, :with_contacts, 10)
end

Upvotes: 3

Related Questions