Passing procs rather than values to build_list and create_list

199 views
Skip to first unread message

Justin Gordon

unread,
Sep 3, 2012, 4:32:42 PM9/3/12
to factor...@googlegroups.com
I think this is an interesting FactoryGirl question. create_list and build_list would be a little more awesome if they allowed a proc, rather than just a variable to be passed for object building args...



Using Rails3, the awesome FactoryGirl gem has a method create_list that takes a strategy, a number of times and then a hash of values to pass into the strategy. (copied fromhttps://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md)

twenty_year_olds = FactoryGirl.create_list(:user, 25, date_of_birth: 20.years.ago)

Suppose that instead of passing "20.years.ago", I want to pass a lambda (or Proc) that gets executed once for each time that that the variable gets read. Is this possible in Ruby or FactoryGirl, or would FactoryGirl have to check each param to see if it's a lambda.

dob_dynamic = -> { random_dob some_param }
twenty_year_olds
= FactoryGirl.create_list(:user, 25, date_of_birth: dob_dynamic )

When I did something like this, I got:

 raise ActiveRecord::AssociationTypeMismatch, message, Object expected, got Proc

I worked around this issue by doing something like this:

  # pass i, b/c times always passes index to proc
 
# dob_dynamic.() invokes dob_dynamic
  create_user
= -> i { create :user, date_of_birth: dob_dynamic.() }
 
25.times &create_user

Any better way to do this?

Reply all
Reply to author
Forward
0 new messages