Factory Girl
Fixture replacement for focused and readable tests
Remove duplication and confusion from your tests using factories.
factory_girl allows you to quickly define prototypes for each of your models and ask for instances with properties that are important to the test at hand.
Quick links:
Install
gem install thoughtbot-factory_girl --source http://gems.github.com
Note: if you install factory_girl using the gem from Github, you’ll need this in your environment.rb if you want to use Rails 2.1’s dependency manager:
config.gem "thoughtbot-factory_girl", :lib => "factory_girl", :source => "http://gems.github.com"
Define
Add factories to test/factories.rb, spec/factories.rb file, or under a test/factories or spec/factories directory:
Factory.define :user do |f|
f.first_name 'John'
f.last_name 'Doe'
end
Factory.define :admin, :parent => :user do |f|
f.admin true
end
Use
# Saved instance
user = Factory(:user)
# Unsaved instance
user = Factory.build(:user)
# Attribute hash
user_attributes = Factory.attributes_for(:user)
# Stubbed object
user_stub = Factory.stub(:user)
# Override attributes
user = Factory(:user, :first_name => 'Joe')
More
Be sure to read the documentation
Check us out on github
Credits
Written by Joe Ferris with contributions from the open source community.
Thanks to thoughtbot for ideas, inspiration, and funding.
Copyright 2008-2009 Joe Ferris and thoughtbot, inc.
Copyright and License
All code is © 2008, thoughtbot, inc. and is released under the MIT License.
Feel free to email us with any questions or feedback.