factory_girl is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance.
Each factory has a name and a set of attributes. The name is used to guess the class of the object by default, but it's possible to explicitly specify it:
It is highly recommended that you have one factory for each class that provides the simplest set of attributes necessary to create an instance of that class. If you're creating ActiveRecord objects, that means that you should only provide attributes that are required through validations and that do not have defaults. Other factories can be created through inheritance to cover common scenarios for each class.
Factories can either be defined anywhere, but will automatically be loaded if they are defined in files at the following locations:
test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb
== Using factories
factory_girl supports several different build strategies: build, create, attributes_for and stub:
# Returns a User instance that's not saved
user = Factory.build(:user)
# Returns a saved User instance
user = Factory.create(:user)
# Returns a hash of attributes that can be used to build a User instance:
attrs = Factory.attributes_for(:user)
# Returns an object with all defined attributes stubbed out:
stub = Factory.stub(:user)
You can use the Factory method as a shortcut for the default build strategy:
# Same as Factory.create :user:
user = Factory(:user)
The default strategy can be overriden:
# Now same as Factory.build(:user)
Factory.define :user, :default_strategy => :build do |u|
...
end
user = Factory(:user)
No matter which startegy is used, it's possible to override the defined attributes by passing a hash:
# Build a User instance and override the first_name property
user = Factory.build(:user, :first_name => 'Joe')
user.first_name
# => "Joe"
== Lazy Attributes
Most factory attributes can be added using static values that are evaluated when the factory is defined, but some attributes (such as associations and other attributes that must be dynamically generated) will need values assigned each time an instance is generated. These "lazy" attributes can be added by passing a block instead of a parameter:
Users' tastes for syntax vary dramatically, but most users are looking for a common feature set. Because of this, factory_girl supports "syntax layers" which provide alternate interfaces. See Factory::Syntax for information about the various layers available.