RSS
 

New In factory_girl: Callbacks

23 Nov

Thoughtbot‘s factory_girl has recently gotten a terrific new feature: callbacks.

They look like this:

Factory(:user) do |u|
  u.after_create { |user_instance| do_something_to(user_instance) }
end

Now, when you use Factory(:user) in your tests, the do_something_to method will be called after the user is saved in the database.  Also notice that you’ll be passed the instance of the user as a block parameter.

There are two other callbacks now available: after_build and after_stub.  These fire pretty much where you’d expect them to. (In practice, I really only use after_create.)

You can mix and match these callbacks on the same factory.  Multiple definitions of the same callback will be executed in the order you provide them:

Factory(:user) do |u|
  u.after_build  { |user_instance| do_something_to(user_instance) }
  u.after_create { do_this_after_create }
  u.after_create { then_do_this }
end

I’m excited about this addition because of how much more flexibility this gives factory_girl.  There are some kludgy parts of my factories.rb files that will be more elegant when refactored with these methods. Accepting these little lambdas to be run later feels very lispy, something I take as a great sign.

For more usage details, check out the ‘callbacks’ section of the README.

And, if you’d like to read more about using Ruby’s blocks this way, Greg Brown has an excellent article on the topic (excerpted from his also-excellent book).

 
2 Comments

Posted in general

 
  • Dan Croak

    Thanks to YOU for the doc patch on this, motivating us to finally “announce” the feature on the blog.

  • Ben Orenstein

    My pleasure. Factory_girl has been extremely useful–I was happy to give back.