Stubs on object creation

277 views
Skip to first unread message

Raul Murciano

unread,
Jun 19, 2008, 3:37:42 AM6/19/08
to factory_girl
Hi all,

I have an external process associated to a model objects creations:
every new user gets an account on an external web service. Before
using factory_girl I had some ugly methods on test_helper to create
user objects, where I stub the web service call before saving the
user:

def some_kind_of_user
u = User.create( ... )
u.foo = 'bar'
...
u.stubs(:create_web_service_account).returns('baz')
u.save
end

Can I stub calls inside a Factory on a similar way? I'm still learning
mocha and factory_girl so I'm possibly missing some point, but I
couldn't find a beautiful way to do so.

Thanks in advance!

Muz

unread,
Jun 19, 2008, 7:30:43 AM6/19/08
to factory_girl
Hi Raul,

I was chatting with some of my colleagues this morning and we came up
with the idea of providing after_build and after_create callbacks in
the factory. Taking your example, you'd do the following:

Factory :user_with_baz_web_service_account, :class => User do |f|
f.foo 'bar'
...
f.after_build do |user|
user.stubs(:create_web_service_account).returns('baz')
end
end

Then if you do Factory(:user_with_baz_web_service_account).create you
get yourself a user that has a stubbed out
create_web_service_account. So, rather than baking stubbing or
mocking into Factories directly, we've just provided hooks that can be
run after the object is built or after it is created where you can do
whatever you want.

I'm sure there are limitations to this, but it might be what you are
looking for. I've made my changes availble on github if you are
interested: http://github.com/h-lame/factory_girl/tree/master

I'd also love to hear what anyone else thinks of such a solution.

Cheers,

Muz

Raul Murciano

unread,
Jun 19, 2008, 11:34:50 AM6/19/08
to factory_girl


On 19 jun, 13:30, Muz <murray.ste...@gmail.com> wrote:
> Hi Raul,
>
> I was chatting with some of my colleagues this morning and we came up
> with the idea of providing after_build and after_create callbacks in
> the factory.  Taking your example, you'd do the following:
>
> Factory :user_with_baz_web_service_account, :class => User do |f|
>   f.foo 'bar'
>   ...
>   f.after_build do |user|
>     user.stubs(:create_web_service_account).returns('baz')
>   end
> end
>

Nice!

> I'm sure there are limitations to this, but it might be what you are
> looking for.  I've made my changes availble on github if you are
> interested:http://github.com/h-lame/factory_girl/tree/master

Of course I am, thank you very much Muz!
Reply all
Reply to author
Forward
0 new messages