[factory_girl] Factory.create passing initialize args

592 views
Skip to first unread message

nitsujri

unread,
May 14, 2010, 9:24:26 PM5/14/10
to factory_girl
Hi guys,

I have a class where:

class foo
def initialize(args)
self.use_args = args[:used]
end
end

and I do a create on Factory.define :foo ... when I call
Factory.create it complains Number of arguements (0 of 1) and it seems
like no amount of passing anything helps get any variables into the
new so it can be passed into args.

Any idea how to get past this? I've done some basic searching to no
avail. Thanks!

Justin

--
Individuals over processes. Interactions over tools. Agile Rails training from thoughtbot, the makers of Clearance, Shoulda, & Factory Girl:
http://thoughtbot.com/services/training

You received this message because you are subscribed to the "factory_girl" mailing list.
To post to this group, send email to factor...@googlegroups.com
To unsubscribe from this group, send email to
factory_girl...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/factory_girl?hl=en

Nathan Sutton

unread,
May 15, 2010, 8:06:28 PM5/15/10
to factor...@googlegroups.com
Factory.create first initializes the the class then assigns each attribute individually. For example...

Suppose you have this:

class Foo < ActiveRecord::Base
end

Factory.define :foo do |f|
f.bar 'baz'
end

If you then ran:

Factory.create(:foo)

It would be the equivalent of running:

f = Foo.new
f.bar = 'baz'
f

Since your initialize method requires and argument, it's breaking on:

f = Foo.new

You could solve it by changing your initialize method to have a default value for args:

class Foo
def initialize(args={})
self.use_args = args[:used]
end
end

In theory, at least. I don't know what your code is like, so that may not work.

By the way, working this way a good thing for factory girl, as it gets around attr_accessible and attr_protected in ActiveRecord. Otherwise you could never assign protected attributes using factory girl, which would suck.

Nate
Reply all
Reply to author
Forward
0 new messages