Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra arguments for Factory Girl

I need to pass extra arguments to factory girl to be used in a callback. Something like this (but more complex really):

Factory.define :blog do |blog|
  blog.name "Blah"

  blog.after_create do |blog|
    blog.posts += sample_posts
    blog.save!
  end
end

and then create it with something like this:

Factory.create(:blog, :sample_posts => [post1, post2])

Any ideas how to do it?

like image 651
pupeno Avatar asked Apr 19 '10 09:04

pupeno


3 Answers

This is now possible without any "hacks" thanks to transient attributes (see comment on issue #49)

example:

FactoryGirl.define do
  factory :user do
    transient do
      bar_extension false
    end
    name {"foo #{' bar' if bar_extension}"}
  end
end

# Factory(:user).name = "foo"
# Factory(:user, :bar_extension => true).name = "foo bar"

For Factory Girl versions < 5.0:

FactoryGirl.define do
  factory :user do
    ignore do
      bar_extension false
    end
    name {"foo #{' bar' if bar_extension}"}
  end
end

# Factory(:user).name = "foo"
# Factory(:user, :bar_extension => true).name = "foo bar"
like image 92
wintersolutions Avatar answered Nov 08 '22 16:11

wintersolutions


Another option would be to use build instead of create and add :autosave to the collection:

class Blog
  has_many :posts, :autosave => true
end

Factory.define :blog do |blog|
  blog.name 'Blah'
  blog.posts { |_| [Factory.build(:post)] }
end

Factory(:blog, :posts => [post1, post2])
#or
Factory.build(:blog, :posts => [unsavedPost1, unsavedPost2])
like image 39
James A. Rosen Avatar answered Nov 08 '22 15:11

James A. Rosen


Apparently, this is not possible at the moment without workarounds that require modifying the model itself. This bug is reported in: http://github.com/thoughtbot/factory_girl/issues#issue/49

like image 2
pupeno Avatar answered Nov 08 '22 16:11

pupeno