Skip to content

New In factory_girl: Callbacks

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 block parameter.

There are two other callbacks now available: after_build and after_stub.  Their callbacks fire pretty much where you’d expect them to.

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 elegantly accomplished with these tools.

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

  1. Dan Croak wrote:

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

    Monday, November 23, 2009 at 9:32 pm | Permalink
  2. Ben Orenstein wrote:

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

    Monday, November 23, 2009 at 10:51 pm | Permalink

Post a Comment

Your email is never published nor shared.