1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00

Updated and improved the documentation

This commit is contained in:
Joe Ferris 2009-02-17 16:38:15 -05:00
parent 43bf67f9ec
commit deeed519d5
11 changed files with 343 additions and 292 deletions

224
README.rdoc Normal file
View file

@ -0,0 +1,224 @@
= factory_girl
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 inheritence.
== Download
Github: http://github.com/thoughtbot/factory_girl/tree/master
Gem:
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"
== Defining factories
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 excplicitly specify it:
# This will guess the User class
Factory.define :user do |u|
u.first_name 'John'
u.last_name 'Doe'
u.admin false
end
# This will use the User class (Admin would have been guessed)
Factory.define :admin, :class => User do |u|
u.first_name 'Admin'
u.last_name 'User'
u.admin true
end
# The same, but using a string instead of class constant
Factory.define :admin, :class => 'user' do |u|
u.first_name 'Admin'
u.last_name 'User'
u.admin true
end
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 inheritence 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:
Factory.define :user do |u|
# ...
u.activation_code { User.generate_activation_code }
end
== Dependent Attributes
Attributes can be based on the values of other attributes using the proxy that is yieled to lazy attribute blocks:
Factory.define :user do |u|
u.first_name 'Joe'
u.last_name 'Blow'
u.email {|a| "#{a.first_name}.#{a.last_name}@example.com".downcase }
end
Factory(:user, :last_name => 'Doe').email
# => "joe.doe@example.com"
== Associations
Associated instances can be generated by using the association method when
defining a lazy attribute:
Factory.define :post do |p|
# ...
p.author {|author| author.association(:user, :last_name => 'Writely') }
end
The behavior of the association method varies depending on the build strategy used for the parent object.
# Builds and saves a User and a Post
post = Factory(:post)
post.new_record? # => false
post.author.new_record # => false
# Builds and saves a User, and then builds but does not save a Post
Factory.build(:post)
post.new_record? # => true
post.author.new_record # => false
Because this pattern is so common, a prettier syntax is available for defining
associations:
# The following definitions are equivilent:
Factory.define :post do |p|
p.author {|a| a.association(:user) }
end
Factory.define :post do |p|
p.association :author, :factory => :user
end
If the factory name is the same as the association name, the factory name can
be left out.
== Inheritance
You can easily create multiple factories for the same class without repeating common attributes by using inheritence:
Factory.define :post do |p|
# the 'title' attribute is required for all posts
p.title 'A title'
end
Factory.define :approved_post, :parent => :post do |p|
p.approved true
# the 'approver' association is required for an approved post
p.association :approver, :factory => :user
end
== Sequences
Unique values in a specific format (for example, e-mail addresses) can be
generated using sequences. Sequences are defined by calling Factory.sequence,
and values in a sequence are generated by calling Factory.next:
# Defines a new sequence
Factory.sequence :email do |n|
"person#{n}@example.com"
end
Factory.next :email
# => "person1@example.com"
Factory.next :email
# => "person2@example.com"
Sequences can be used in lazy attributes:
Factory.define :user do |f|
f.email { Factory.next(:email) }
end
And it's also possible to define an in-line sequence that is only used in
a particular factory:
Factory.define :user do |f|
f.sequence :email {|n| "person#{n}@example.com" }
end
== Alternate Syntaxes
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.
== More Information
Our blog: http://giantrobots.thoughtbot.com
factory_girl rdoc: http://dev.thoughtbot.com/factory_girl
Mailing list: http://groups.google.com/group/factory_girl
factory_girl tickets: http://thoughtbot.lighthouseapp.com/projects/14354-factory_girl
== Contributing
Please read the contribution guidelines before submitting patches or pull requests.
== Author
factory_girl was written by Joe Ferris with contributions from several authors, including:
* Alex Sharp
* Eugene Bolshakov
* Jon Yurek
* Josh Nichols
* Josh Owens
Thanks to all members of thoughtbot for inspiration, ideas, and funding.
Copyright 2008-2009 Joe Ferris and thoughtbot[http://www.thoughtbot.com], inc.

View file

@ -1,213 +0,0 @@
h1. factory_girl
factory_girl is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and mock objects), and support for multiple factories for the same class (user, admin_user, and so on).
Written by "Joe Ferris":mailto:jferris@thoughtbot.com.
Thanks to Tammer Saleh, Dan Croak, and Jon Yurek of thoughtbot, inc.
Copyright 2008 Joe Ferris and thoughtbot, inc.
h2. Download
Github: "Page":http://github.com/thoughtbot/factory_girl/tree/master "Clone":git://github.com/thoughtbot/factory_girl.git
Gem: <pre>gem install thoughtbot-factory_girl --source http://gems.github.com</pre>
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"
h2. Defining factories
Each factory has a name and a bunch of attributes. The name is used to guess the class of the object by default, but it's possible to excplicitly specify it:
<pre><code># This will guess the User class
Factory.define :user do |u|
u.first_name 'John'
u.last_name 'Doe'
u.admin false
end
# This will use the User class (Admin would have been guessed)
Factory.define :admin, :class => User do |u|
u.first_name 'Admin'
u.last_name 'User'
u.admin true
end
# The same, but using a string instead of class constant
Factory.define :admin, :class => 'user' do |u|
u.first_name 'Admin'
u.last_name 'User'
u.admin true
end
</code></pre>
Factories can either be defined in test/factories.rb file or in separate files
under test/factories or test/spec
h2. Using factories
factory_girl will automatically load factory definitions if you place your them in 'test/factories.rb', 'spec/factories.rb', or in individual files underneath the 'test/factories' and 'spec/factories' directories.
factory_girl supports several different build strategies: build, create, attribtues_for and stub:
<pre><code># 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 a mock object with all defined attributes stubbed out:
mock = Factory.stub(:user)
</pre></code>
The default is "create" and it's used by the Factory shortcut method:
<pre><code># Same as Factory.create :user:
user = Factory :user
</pre></code>
The default strategy can be overriden with the :default_strategy_parameter though:
<pre><code># Now same as Factory.build :user
Factory.define :user, :default_strategy => :build do |u|
....
end
user = Factory :user
</pre></code>
No matter which startegy is used, it's possible to override the attributes by passing a hash:
<pre><code># Build a User instance and override the first_name property
user = Factory.build(:user, :first_name => 'Joe')
user.first_name
# => "Joe"
</code></pre>
h2. 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:
<pre><code>Factory.define :user do |u|
# ...
u.activation_code { User.generate_activation_code }
end</code></pre>
h2. Dependent Attributes
Some attributes may need to be generated based on the values of other attributes. This can be done by calling the attribute name on Factory::AttributeProxy, which is yielded to lazy attribute blocks:
<pre><code>Factory.define :user do |u|
u.first_name 'Joe'
u.last_name 'Blow'
u.email {|a| "#{a.first_name}.#{a.last_name}@example.com".downcase }
end
Factory(:user, :last_name => 'Doe').email
# => "joe.doe@example.com"</code></pre>
h2. Associations
Associated instances can be generated by using the association method when
defining a lazy attribute:
<pre><code>Factory.define :post do |p|
# ...
p.author {|author| author.association(:user, :last_name => 'Writely') }
end</code></pre>
When using the association method, the same build strategy will be used for all generated instances:
<pre><code># Builds and saves a User and a Post
post = Factory(:post)
post.new_record? # => false
post.author.new_record # => false
# Builds but does not save a User and a Post
Factory.build(:post)
post.new_record? # => true
post.author.new_record # => true</code></pre>
Because this pattern is so common, a prettier syntax is available for defining
associations:
<pre><code># The following definitions are equivilent:
Factory.define :post do |p|
p.author {|a| a.association(:user) }
end
Factory.define :post do |p|
p.association :author, :factory => :user
end</code></pre>
If the factory name is the same as the association name, the factory name can
be left out.
h2. Inheritance
In case there are several factories for the same class that share common attributes, you can define them in a parent factory and inherit other ones from it. A child factory can override parent attributes and define new ones:
<pre><code>
Factory.define :user do |u|
u.first_name 'John'
u.last_name 'Doe'
u.admin false
end
Factory.define :admin, :parent => :user do |u|
u.admin true
end</code></pre>
Factory.define :guest, :parent => :user do |u|
u.last_name 'Anonymous'
u.guest true
end</code></pre>
h2. Sequences
Unique values in a specific format (for example, e-mail addresses) can be
generated using sequences. Sequences are defined by calling Factory.sequence,
and values in a sequence are generated by calling Factory.next:
<pre><code># Defines a new sequence
Factory.sequence :email do |n|
"person#{n}@example.com"
end
Factory.next :email
# => "person1@example.com"
Factory.next :email
# => "person2@example.com"</code></pre>
Sequences can be used as lazy attributes:
Factory.define :user do |f|
f.email { Factory.next(:email) }
end
And it's also possible to define an in-line sequence that is only used in
a particular factory:
h2. More Information
"Our blog":http://giantrobots.thoughtbot.com
"factory_girl rdoc":http://dev.thoughtbot.com/factory_girl
"Mailing list":http://groups.google.com/group/factory_girl
"factory_girl tickets":http://thoughtbot.lighthouseapp.com/projects/14354-factory_girl
h2. Contributing
Please read the contribution guidelines before submitting patches or pull requests.

View file

@ -28,8 +28,8 @@ desc 'Generate documentation for the factory_girl plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'Factory Girl'
rdoc.options << '--line-numbers' << '--inline-source' << "--main" << "README.textile"
rdoc.rdoc_files.include('README.textile')
rdoc.options << '--line-numbers' << '--inline-source' << "--main" << "README.rdoc"
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('lib/**/*.rb')
end
@ -52,8 +52,8 @@ spec = Gem::Specification.new do |s|
s.test_files = Dir[*['test/**/*_test.rb']]
s.has_rdoc = true
s.extra_rdoc_files = ["README.textile"]
s.rdoc_options = ['--line-numbers', '--inline-source', "--main", "README.textile"]
s.extra_rdoc_files = ["README.rdoc"]
s.rdoc_options = ['--line-numbers', '--inline-source', "--main", "README.rdoc"]
s.authors = ["Joe Ferris"]
s.email = %q{jferris@thoughtbot.com}

View file

@ -8,19 +8,30 @@ class Factory
[/(.*)/, '\1_id']
]
# Defines a new alias for attributes
# Defines a new alias for attributes.
#
# Arguments:
# pattern: (Regexp)
# A pattern that will be matched against attributes when looking for
# aliases. Contents captured in the pattern can be used in the alias.
# replace: (String)
# The alias that results from the matched pattern. Captured strings can
# be insert like String#sub.
# * pattern: +Regexp+
# A pattern that will be matched against attributes when looking for
# aliases. Contents captured in the pattern can be used in the alias.
# * replace: +String+
# The alias that results from the matched pattern. Captured strings can
# be substituded like with +String#sub+.
#
# Example:
#
# Factory.alias /(.*)_confirmation/, '\1'
#
# factory_girl starts with aliases for foreign keys, so that a :user
# association can be overridden by a :user_id parameter:
#
# Factory.define :post do |p|
# p.association :user
# end
#
# # The user association will not be built in this example. The user_id
# # will be used instead.
# Factory(:post, :user_id => 1)
def self.alias (pattern, replace)
self.aliases << [pattern, replace]
end

View file

@ -1,5 +1,9 @@
class Factory
# Raised when defining an invalid attribute:
# * Defining an attribute which has a name ending in "="
# * Defining an attribute with both a static and lazy value
# * Defining an attribute twice in the same factory
class AttributeDefinitionError < RuntimeError
end

View file

@ -1,5 +1,6 @@
class Factory
# Raised when a factory is defined that attempts to instantiate itself.
class AssociationDefinitionError < RuntimeError
end
@ -16,27 +17,30 @@ class Factory
self.factories = {}
self.definition_file_paths = %w(factories test/factories spec/factories)
attr_reader :factory_name
attr_reader :factory_name #:nodoc:
attr_reader :attributes #:nodoc:
# Defines a new factory that can be used by the build strategies (create and
# build) to build new objects.
#
# Arguments:
# name: (Symbol)
# A unique name used to identify this factory.
# options: (Hash)
# class: the class that will be used when generating instances for this
# factory. If not specified, the class will be guessed from the
# factory name.
# parent: the parent factory. If specified, the attributes from the parent
# factory will be copied to the current one with an ability to
# override them
# default_strategy: the strategy that will be used by the Factory shortcut method.
# Default is :create
# * name: +Symbol+ or +String+
# A unique name used to identify this factory.
# * options: +Hash+
#
# Yields:
# The newly created factory (Factory)
# Options:
# * class: +Symbol+, +Class+, or +String+
# The class that will be used when generating instances for this factory. If not specified, the class will be guessed from the factory name.
# * parent: +Symbol+
# The parent factory. If specified, the attributes from the parent
# factory will be copied to the current one with an ability to override
# them.
# * default_strategy: +Symbol+
# The strategy that will be used by the Factory shortcut method.
# Defaults to :create.
#
# Yields: +Factory+
# The newly created factory.
def self.define (name, options = {})
instance = Factory.new(name, options)
yield(instance)
@ -46,7 +50,7 @@ class Factory
self.factories[instance.factory_name] = instance
end
def class_name #:nodoc
def class_name #:nodoc:
@options[:class] || factory_name
end
@ -87,11 +91,11 @@ class Factory
# strategy.
#
# Arguments:
# name: (Symbol)
# The name of this attribute. This will be assigned using :"#{name}=" for
# generated instances.
# value: (Object)
# If no block is given, this value will be used for this attribute.
# * name: +Symbol+ or +String+
# The name of this attribute. This will be assigned using :"#{name}=" for
# generated instances.
# * value: +Object+
# If no block is given, this value will be used for this attribute.
def add_attribute (name, value = nil, &block)
if block_given?
if value
@ -141,14 +145,16 @@ class Factory
# end
#
# Arguments:
# name: (Symbol)
# The name of this attribute.
# options: (Hash)
# factory: (Symbol)
# The name of the factory to use when building the associated instance.
# If no name is given, the name of the attribute is assumed to be the
# name of the factory. For example, a "user" association will by
# default use the "user" factory.
# * name: +Symbol+
# The name of this attribute.
# * options: +Hash+
#
# Options:
# * factory: +Symbol+ or +String+
# The name of the factory to use when building the associated instance.
# If no name is given, the name of the attribute is assumed to be the
# name of the factory. For example, a "user" association will by
# default use the "user" factory.
def association (name, options = {})
factory_name = options.delete(:factory) || name
if factory_name_for(factory_name) == self.factory_name
@ -156,25 +162,23 @@ class Factory
end
@attributes << Attribute::Association.new(name, factory_name, options)
end
# Adds an attribute that will have unique values generated by a sequence with
# a specified format.
#
#
# The result of:
# Factory.define :user do |f|
# f.sequence(:email) { |n| "person#{n}@example.com" }
# end
#
# Factory.define :user do |f|
# f.sequence(:email) { |n| "person#{n}@example.com" }
# end
#
# Is equal to:
# Factory.sequence(:email) { |n| "person#{n}@example.com" }
#
# Factory.sequence(:email) { |n| "person#{n}@example.com" }
# Factory.define :user do |f|
# f.email { Factory.next(:email) }
# end
#
# Factory.define :user do |f|
# f.email { Factory.next(:email) }
# end
#
# Except that no globally available sequence will be defined
# Except that no globally available sequence will be defined.
def sequence (name, &block)
s = Sequence.new(&block)
add_attribute(name) { s.next }
@ -185,12 +189,14 @@ class Factory
# pairs.
#
# Arguments:
# overrides: (Hash)
# Attributes to overwrite for this set.
# * name: +Symbol+ or +String+
# The name of the factory that should be used.
# * overrides: +Hash+
# Attributes to overwrite for this set.
#
# Returns:
# A set of attributes that can be used to build an instance of the class
# this factory generates. (Hash)
# Returns: +Hash+
# A set of attributes that can be used to build an instance of the class
# this factory generates.
def self.attributes_for (name, overrides = {})
factory_by_name(name).run(Proxy::AttributesFor, overrides)
end
@ -199,12 +205,14 @@ class Factory
# individually overridden by passing in a Hash of attribute => value pairs.
#
# Arguments:
# overrides: (Hash)
# See attributes_for
# * name: +Symbol+ or +String+
# The name of the factory that should be used.
# * overrides: +Hash+
# Attributes to overwrite for this instance.
#
# Returns:
# An instance of the class this factory generates, with generated
# attributes assigned.
# Returns: +Object+
# An instance of the class this factory generates, with generated attributes
# assigned.
def self.build (name, overrides = {})
factory_by_name(name).run(Proxy::Build, overrides)
end
@ -213,34 +221,49 @@ class Factory
# be individually overridden by passing in a Hash of attribute => value
# pairs.
#
# If the instance is not valid, an ActiveRecord::Invalid exception will be
# raised.
# Instances are saved using the +save!+ method, so ActiveRecord models will
# raise ActiveRecord::RecordInvalid exceptions for invalid attribute sets.
#
# Arguments:
# overrides: (Hash)
# See attributes_for
# * name: +Symbol+ or +String+
# The name of the factory that should be used.
# * overrides: +Hash+
# Attributes to overwrite for this instance.
#
# Returns:
# A saved instance of the class this factory generates, with generated
# attributes assigned.
# Returns: +Object+
# A saved instance of the class this factory generates, with generated
# attributes assigned.
def self.create (name, overrides = {})
factory_by_name(name).run(Proxy::Create, overrides)
end
# Generates and returns a mock object with all attributes from this factory stubbed out.
# Attributes can be individually overridden by passing in a Hash of attribute => value
# pairs.
# Generates and returns an object with all attributes from this factory
# stubbed out. Attributes can be individually overridden by passing in a Hash
# of attribute => value pairs.
#
# Arguments:
# overrides: (Hash)
# Attributes to overwrite for this set.
# * name: +Symbol+ or +String+
# The name of the factory that should be used.
# * overrides: +Hash+
# Attributes to overwrite for this instance.
#
# Returns:
# A mock object with generated attributes stubbed out (Object)
# Returns: +Object+
# An object with generated attributes stubbed out.
def self.stub (name, overrides = {})
factory_by_name(name).run(Proxy::Stub, overrides)
end
# Executes the default strategy for the given factory. This is usually create,
# but it can be overridden for each factory.
#
# Arguments:
# * name: +Symbol+ or +String+
# The name of the factory that should be used.
# * overrides: +Hash+
# Attributes to overwrite for this instance.
#
# Returns: +Object+
# The result of the default strategy.
def self.default_strategy (name, overrides = {})
self.send(factory_by_name(name).default_strategy, name, overrides)
end

View file

@ -1,6 +1,6 @@
class Factory
class Proxy #:nodoc:
class AttributesFor < Proxy
class AttributesFor < Proxy #:nodoc:
def initialize(klass)
@hash = {}
end

View file

@ -1,6 +1,6 @@
class Factory
class Proxy #:nodoc:
class Build < Proxy
class Build < Proxy #:nodoc:
def initialize(klass)
@instance = klass.new
end

View file

@ -1,6 +1,6 @@
class Factory
class Proxy #:nodoc:
class Create < Build
class Create < Build #:nodoc:
def result
@instance.save!
@instance

View file

@ -1,6 +1,6 @@
class Factory
class Proxy
class Stub < Proxy
class Stub < Proxy #:nodoc:
def initialize(klass)
@mock = Object.new
end

View file

@ -1,5 +1,7 @@
class Factory
# Sequences are defined using Factory.sequence. Sequence values are generated
# using next.
class Sequence
def initialize (&proc) #:nodoc: