Like most people who started with Rails a while back, I first loved Rails fixtures and ended up hating them (slow, a pain to maintain etc…).
You might not feel the need for a decent fixtures solution if you do a lot of mocking/stubbing, but I recently came back from my “mock everything you can outside of models” approach and I’m getting closer to the mock roles, not objects approach. So, I’m loosing my model/controller testing separation but I’m gaining by not having to maintain “dumb mocks” which don’t always represent the real API behind. I mean, how many times did I change a Model, messing up my app but all my specs were still passing. Anyway, that’s a long discussion, which will be covered by wycats during merbcamp
So here is a simple example of how I use factory girl in a Merb + DataMapper app. (you can do the same in a Rails app, there is nothing specific to Merb in factory_girl).
I. create an empty app, set the ORM etc…
III. create a spec/factories.rb file. (You might prefer to create a folder called spec/factories and add a factory per model)
IV. modify spec_helper.rb and add the following
require ‘factory_girl’ require File.dirname(FILE) + ‘/factories’
V. write some specs against a Client model
VI. Create the Model
VII. create a factory
* IIX. run your specs
IX. fix the model (note that I set
dependencies "dm-validations" in my init.rb)
- X. run the specs
- XI. add more specs
As you can see, Factory.build(:client) only creates a new instance of the Object, while Factory(:client) creates, saves and loads the instance.
- XII. get them to pass
Factory Girl makes fixtures simple and clean. Here is another example for creating associations:
Factory Girl also supports sequencing, check out FG read me