Palash Kulkarni
Palash Kulkarni

Reputation: 11

FactoryGirl rspec, while creating multiple factories at once

When I am creating multiple object of Factory using method create_list, the order and where method don't work on it because create_list creates the array of factory objects.

users = FactoryGirl.create_list(:user, 5)
users.order('name ASC')

It gives undefined method order for Array

So, what should I do to create the multiple factory objects inside the ActiveRecord Collection?

Upvotes: 1

Views: 1115

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54674

The order and where methods are not defined on Array but on ActiveRecord::Relation. It's the kind of thing that gets passed around by the ActiveRecord query interface. You simply cannot run a query on an array. To run a query you need to start from scratch:

create_list, :user, 5
users = User.where(...).order(name: :asc)

But you might as well directly pass your arguments to create_list so that the condition is satisfied without needing to re-select the users. I also often find myself writing arrays explicitly when I need to alter values in each row e. g.

users = [
  create(:user, name: 'Alfred'),
  create(:user, name: 'Bob'),
  create(:user, name: 'Charlie'),
  create(:user, name: 'David'),
  create(:user, name: 'Egon')
]

The users are already ordered by name and you're good to go. If you have some condition in the where clause that for example separates the users in two groups, you can just go ahead and separate these users directly. For example imagine we have an admin flag in the users table and you want to create many users, some being admins and some not. Then you'd do

admins = [
  create(:user, name: 'Alfred', admin: true),
  create(:user, name: 'Charlie', admin: true),
  create(:user, name: 'Egon', admin: true)
]

visitors = [
  create(:user, name: 'Bob'),
  create(:user, name: 'David')
]

No need to query at all. Of course you can also do that in let syntax if you like.

Upvotes: 1

Related Questions