Make the examples use Ruby syntax highlighting on GitHub.

This commit is contained in:
Daniel Schierbeck 2012-01-13 17:44:27 +01:00 committed by Joshua Clayton
parent 32ff41ffbe
commit 1e828893f1
1 changed files with 354 additions and 278 deletions

View File

@ -6,11 +6,15 @@ Update Your Gemfile
If you're using Rails, you'll need to change the required version of `factory_girl_rails`: If you're using Rails, you'll need to change the required version of `factory_girl_rails`:
gem "factory_girl_rails", "~> 1.2" ```ruby
gem "factory_girl_rails", "~> 1.2"
```
If you're *not* using Rails, you'll just have to change the required version of `factory_girl`: If you're *not* using Rails, you'll just have to change the required version of `factory_girl`:
gem "factory_girl", "~> 2.1.0" ```ruby
gem "factory_girl", "~> 2.1.0"
```
Once your Gemfile is updated, you'll want to update your bundle. Once your Gemfile is updated, you'll want to update your bundle.
@ -19,28 +23,30 @@ 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 explicitly specify it: 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:
# This will guess the User class ```ruby
FactoryGirl.define do # This will guess the User class
factory :user do FactoryGirl.define do
first_name 'John' factory :user do
last_name 'Doe' first_name 'John'
admin false last_name 'Doe'
end admin false
end
# This will use the User class (Admin would have been guessed) # This will use the User class (Admin would have been guessed)
factory :admin, :class => User do factory :admin, :class => User do
first_name 'Admin' first_name 'Admin'
last_name 'User' last_name 'User'
admin true admin true
end end
# The same, but using a string instead of class constant # The same, but using a string instead of class constant
factory :admin, :class => 'user' do factory :admin, :class => 'user' do
first_name 'Admin' first_name 'Admin'
last_name 'User' last_name 'User'
admin true admin true
end end
end 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 inheritance to cover common scenarios for each class. 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.
@ -59,49 +65,57 @@ Using factories
factory\_girl supports several different build strategies: build, create, attributes\_for and stub: factory\_girl supports several different build strategies: build, create, attributes\_for and stub:
# Returns a User instance that's not saved ```ruby
user = FactoryGirl.build(:user) # Returns a User instance that's not saved
user = FactoryGirl.build(:user)
# Returns a saved User instance # Returns a saved User instance
user = FactoryGirl.create(:user) user = FactoryGirl.create(:user)
# Returns a hash of attributes that can be used to build a User instance # Returns a hash of attributes that can be used to build a User instance
attrs = FactoryGirl.attributes_for(:user) attrs = FactoryGirl.attributes_for(:user)
# Returns an object with all defined attributes stubbed out # Returns an object with all defined attributes stubbed out
stub = FactoryGirl.build_stubbed(:user) stub = FactoryGirl.build_stubbed(:user)
# Passing a block to any of the methods above will yield the return object # Passing a block to any of the methods above will yield the return object
FactoryGirl.create(:user) do |user| FactoryGirl.create(:user) do |user|
user.posts.create(attributes_for(:post)) user.posts.create(attributes_for(:post))
end end
```
No matter which strategy is used, it's possible to override the defined attributes by passing a hash: No matter which strategy is used, it's possible to override the defined attributes by passing a hash:
# Build a User instance and override the first_name property ```ruby
user = FactoryGirl.build(:user, :first_name => 'Joe') # Build a User instance and override the first_name property
user.first_name user = FactoryGirl.build(:user, :first_name => 'Joe')
# => "Joe" user.first_name
# => "Joe"
```
If repeating "FactoryGirl" is too verbose for you, you can mix the syntax methods in: If repeating "FactoryGirl" is too verbose for you, you can mix the syntax methods in:
# rspec ```ruby
RSpec.configure do |config| # rspec
config.include FactoryGirl::Syntax::Methods RSpec.configure do |config|
end config.include FactoryGirl::Syntax::Methods
end
# Test::Unit # Test::Unit
class Test::Unit::TestCase class Test::Unit::TestCase
include Factory::Syntax::Methods include Factory::Syntax::Methods
end end
```
This would allow you to write: This would allow you to write:
describe User, "#full_name" do ```ruby
subject { create(:user, :first_name => "John", :last_name => "Doe") } describe User, "#full_name" do
subject { create(:user, :first_name => "John", :last_name => "Doe") }
its(:full_name) { should == "John Doe" } its(:full_name) { should == "John Doe" }
end end
```
Lazy Attributes Lazy Attributes
--------------- ---------------
@ -112,73 +126,81 @@ 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 time an instance is generated. These "lazy" attributes can be added by passing a
block instead of a parameter: block instead of a parameter:
factory :user do ```ruby
# ... factory :user do
activation_code { User.generate_activation_code } # ...
date_of_birth { 21.years.ago } activation_code { User.generate_activation_code }
end date_of_birth { 21.years.ago }
end
```
Aliases Aliases
------- -------
Aliases allow you to use named associations more easily. Aliases allow you to use named associations more easily.
factory :user, :aliases => [:author, :commenter] do ```ruby
first_name "John" factory :user, :aliases => [:author, :commenter] do
last_name "Doe" first_name "John"
date_of_birth { 18.years.ago } last_name "Doe"
end date_of_birth { 18.years.ago }
end
factory :post do factory :post do
author author
# instead of # instead of
# association :author, :factory => :user # association :author, :factory => :user
title "How to read a book effectively" title "How to read a book effectively"
body "There are five steps involved." body "There are five steps involved."
end end
factory :comment do factory :comment do
commenter commenter
# instead of # instead of
# association :commenter, :factory => :user # association :commenter, :factory => :user
body "Great article!" body "Great article!"
end end
```
Dependent Attributes Dependent Attributes
-------------------- --------------------
Attributes can be based on the values of other attributes using the proxy that is yielded to lazy attribute blocks: Attributes can be based on the values of other attributes using the proxy that is yielded to lazy attribute blocks:
factory :user do ```ruby
first_name 'Joe' factory :user do
last_name 'Blow' first_name 'Joe'
email { "#{first_name}.#{last_name}@example.com".downcase } last_name 'Blow'
end email { "#{first_name}.#{last_name}@example.com".downcase }
end
FactoryGirl.create(:user, :last_name => 'Doe').email FactoryGirl.create(:user, :last_name => 'Doe').email
# => "joe.doe@example.com" # => "joe.doe@example.com"
```
Transient Attributes Transient Attributes
-------------------- --------------------
There may be times where your code can be DRYed up by passing in transient attributes to factories. There may be times where your code can be DRYed up by passing in transient attributes to factories.
factory :user do ```ruby
ignore do factory :user do
rockstar true ignore do
upcased { false } rockstar true
end upcased { false }
end
name { "John Doe#{" - Rockstar" if rockstar}" } name { "John Doe#{" - Rockstar" if rockstar}" }
email { "#{name.downcase}@example.com" } email { "#{name.downcase}@example.com" }
after_create do |user, proxy| after_create do |user, proxy|
user.name.upcase! if proxy.upcased user.name.upcase! if proxy.upcased
end end
end end
FactoryGirl.create(:user, :upcased => true).name FactoryGirl.create(:user, :upcased => true).name
#=> "JOHN DOE - ROCKSTAR" #=> "JOHN DOE - ROCKSTAR"
```
Static and dynamic attributes can be ignored. Ignored attributes will be ignored Static and dynamic attributes can be ignored. Ignored attributes will be ignored
within attributes\_for and won't be set on the model, even if the attribute within attributes\_for and won't be set on the model, even if the attribute
@ -194,68 +216,80 @@ Associations
It's possible to set up associations within factories. If the factory name is the same as the association name, the factory name can be left out. It's possible to set up associations within factories. If the factory name is the same as the association name, the factory name can be left out.
factory :post do ```ruby
# ... factory :post do
author # ...
end author
end
```
You can also specify a different factory or override attributes: You can also specify a different factory or override attributes:
factory :post do ```ruby
# ... factory :post do
association :author, :factory => :user, :last_name => 'Writely' # ...
end association :author, :factory => :user, :last_name => 'Writely'
end
```
The behavior of the association method varies depending on the build strategy used for the parent object. 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 ```ruby
post = FactoryGirl.create(:post) # Builds and saves a User and a Post
post.new_record? # => false post = FactoryGirl.create(:post)
post.author.new_record? # => false post.new_record? # => false
post.author.new_record? # => false
# Builds and saves a User, and then builds but does not save a Post # Builds and saves a User, and then builds but does not save a Post
post = FactoryGirl.build(:post) post = FactoryGirl.build(:post)
post.new_record? # => true post.new_record? # => true
post.author.new_record? # => false post.author.new_record? # => false
```
To not save the associated object, specify :method => :build in the factory: To not save the associated object, specify :method => :build in the factory:
factory :post do ```ruby
# ... factory :post do
association :author, :factory => :user, :method => :build # ...
end association :author, :factory => :user, :method => :build
end
# Builds a User, and then builds a Post, but does not save either # Builds a User, and then builds a Post, but does not save either
post = FactoryGirl.build(:post) post = FactoryGirl.build(:post)
post.new_record? # => true post.new_record? # => true
post.author.new_record? # => true post.author.new_record? # => true
```
Inheritance Inheritance
----------- -----------
You can easily create multiple factories for the same class without repeating common attributes by nesting factories: You can easily create multiple factories for the same class without repeating common attributes by nesting factories:
factory :post do ```ruby
title 'A title' factory :post do
title 'A title'
factory :approved_post do factory :approved_post do
approved true approved true
end end
end end
approved_post = FactoryGirl.create(:approved_post) approved_post = FactoryGirl.create(:approved_post)
approved_post.title # => 'A title' approved_post.title # => 'A title'
approved_post.approved # => true approved_post.approved # => true
```
You can also assign the parent explicitly: You can also assign the parent explicitly:
factory :post do ```ruby
title 'A title' factory :post do
end title 'A title'
end
factory :approved_post, :parent => :post do factory :approved_post, :parent => :post do
approved true approved true
end end
```
As mentioned above, it's good practice to define a basic factory for each class As mentioned above, it's good practice to define a basic factory for each class
with only the attributes required to create it. Then, create more specific with only the attributes required to create it. Then, create more specific
@ -270,49 +304,61 @@ generated using sequences. Sequences are defined by calling sequence in a
definition block, and values in a sequence are generated by calling definition block, and values in a sequence are generated by calling
FactoryGirl.generate: FactoryGirl.generate:
# Defines a new sequence ```ruby
FactoryGirl.define do # Defines a new sequence
sequence :email do |n| FactoryGirl.define do
"person#{n}@example.com" sequence :email do |n|
end "person#{n}@example.com"
end end
end
FactoryGirl.generate :email FactoryGirl.generate :email
# => "person1@example.com" # => "person1@example.com"
FactoryGirl.generate :email FactoryGirl.generate :email
# => "person2@example.com" # => "person2@example.com"
```
Sequences can be used as attributes: Sequences can be used as attributes:
factory :user do ```ruby
email factory :user do
end email
end
```
Or in lazy attributes: Or in lazy attributes:
factory :invite do ```ruby
invitee { FactoryGirl.generate(:email) } factory :invite do
end invitee { FactoryGirl.generate(:email) }
end
```
And it's also possible to define an in-line sequence that is only used in And it's also possible to define an in-line sequence that is only used in
a particular factory: a particular factory:
factory :user do ```ruby
sequence(:email) {|n| "person#{n}@example.com" } factory :user do
end sequence(:email) {|n| "person#{n}@example.com" }
end
```
You can also override the initial value: You can also override the initial value:
factory :user do ```ruby
sequence(:email, 1000) {|n| "person#{n}@example.com" } factory :user do
end sequence(:email, 1000) {|n| "person#{n}@example.com" }
end
```
Without a block, the value will increment itself, starting at its initial value: Without a block, the value will increment itself, starting at its initial value:
factory :post do ```ruby
sequence(:position) factory :post do
end sequence(:position)
end
```
Traits Traits
------ ------
@ -320,107 +366,117 @@ Traits
Traits allow you to group attributes together and then apply them Traits allow you to group attributes together and then apply them
to any factory. to any factory.
factory :user, :aliases => [:author] ```ruby
factory :user, :aliases => [:author]
factory :story do factory :story do
title "My awesome story" title "My awesome story"
author author
trait :published do trait :published do
published true published true
end end
trait :unpublished do trait :unpublished do
published false published false
end end
trait :week_long_publishing do trait :week_long_publishing do
start_at { 1.week.ago } start_at { 1.week.ago }
end_at { Time.now } end_at { Time.now }
end end
trait :month_long_publishing do trait :month_long_publishing do
start_at { 1.month.ago } start_at { 1.month.ago }
end_at { Time.now } end_at { Time.now }
end end
factory :week_long_published_story, :traits => [:published, :week_long_publishing] factory :week_long_published_story, :traits => [:published, :week_long_publishing]
factory :month_long_published_story, :traits => [:published, :month_long_publishing] factory :month_long_published_story, :traits => [:published, :month_long_publishing]
factory :week_long_unpublished_story, :traits => [:unpublished, :week_long_publishing] factory :week_long_unpublished_story, :traits => [:unpublished, :week_long_publishing]
factory :month_long_unpublished_story, :traits => [:unpublished, :month_long_publishing] factory :month_long_unpublished_story, :traits => [:unpublished, :month_long_publishing]
end end
```
Traits can be used as attributes: Traits can be used as attributes:
factory :week_long_published_story_with_title, :parent => :story do ```ruby
published factory :week_long_published_story_with_title, :parent => :story do
week_long_publishing published
title { "Publishing that was started at {start_at}" } week_long_publishing
end title { "Publishing that was started at {start_at}" }
end
```
Traits that define the same attributes won't raise AttributeDefinitionErrors; Traits that define the same attributes won't raise AttributeDefinitionErrors;
the trait that defines the attribute latest gets precedence. the trait that defines the attribute latest gets precedence.
factory :user do ```ruby
name "Friendly User" factory :user do
login { name } name "Friendly User"
login { name }
trait :male do trait :male do
name "John Doe" name "John Doe"
gender "Male" gender "Male"
login { "#{name} (M)" } login { "#{name} (M)" }
end end
trait :female do trait :female do
name "Jane Doe" name "Jane Doe"
gender "Female" gender "Female"
login { "#{name} (F)" } login { "#{name} (F)" }
end end
trait :admin do trait :admin do
admin true admin true
login { "admin-#{name}" } login { "admin-#{name}" }
end end
factory :male_admin, :traits => [:male, :admin] # login will be "admin-John Doe" factory :male_admin, :traits => [:male, :admin] # login will be "admin-John Doe"
factory :female_admin, :traits => [:admin, :female] # login will be "Jane Doe (F)" factory :female_admin, :traits => [:admin, :female] # login will be "Jane Doe (F)"
end end
```
You can also override individual attributes granted by a trait in subclasses. You can also override individual attributes granted by a trait in subclasses.
factory :user do ```ruby
name "Friendly User" factory :user do
login { name } name "Friendly User"
login { name }
trait :male do trait :male do
name "John Doe" name "John Doe"
gender "Male" gender "Male"
login { "#{name} (M)" } login { "#{name} (M)" }
end end
factory :brandon do factory :brandon do
male male
name "Brandon" name "Brandon"
end end
end end
```
Traits can also be passed in as a list of symbols when you construct an instance from FactoryGirl. Traits can also be passed in as a list of symbols when you construct an instance from FactoryGirl.
factory :user do ```ruby
name "Friendly User" factory :user do
name "Friendly User"
trait :male do trait :male do
name "John Doe" name "John Doe"
gender "Male" gender "Male"
end end
trait :admin do trait :admin do
admin true admin true
end end
end end
# creates an admin user with gender "Male" and name "Jon Snow" # creates an admin user with gender "Male" and name "Jon Snow"
FactoryGirl.create(:user, :admin, :male, :name => "Jon Snow") FactoryGirl.create(:user, :admin, :male, :name => "Jon Snow")
```
This ability works with `build`, `build_stubbed`, `attributes_for`, and `create`. This ability works with `build`, `build_stubbed`, `attributes_for`, and `create`.
@ -435,26 +491,32 @@ factory\_girl makes available three callbacks for injecting some code:
Examples: Examples:
# Define a factory that calls the generate_hashed_password method after it is built ```ruby
factory :user do # Define a factory that calls the generate_hashed_password method after it is built
after_build { |user| generate_hashed_password(user) } factory :user do
end after_build { |user| generate_hashed_password(user) }
end
```
Note that you'll have an instance of the user in the block. This can be useful. Note that you'll have an instance of the user in the block. This can be useful.
You can also define multiple types of callbacks on the same factory: You can also define multiple types of callbacks on the same factory:
factory :user do ```ruby
after_build { |user| do_something_to(user) } factory :user do
after_create { |user| do_something_else_to(user) } after_build { |user| do_something_to(user) }
end after_create { |user| do_something_else_to(user) }
end
```
Factories can also define any number of the same kind of callback. These callbacks will be executed in the order they are specified: Factories can also define any number of the same kind of callback. These callbacks will be executed in the order they are specified:
factory :user do ```ruby
after_create { this_runs_first } factory :user do
after_create { then_this } after_create { this_runs_first }
end after_create { then_this }
end
```
Calling FactoryGirl.create will invoke both after\_build and after\_create callbacks. Calling FactoryGirl.create will invoke both after\_build and after\_create callbacks.
@ -468,35 +530,41 @@ modify that factory instead of creating a child factory and adding attributes th
If a gem were to give you a User factory: If a gem were to give you a User factory:
FactoryGirl.define do ```ruby
factory :user do FactoryGirl.define do
full_name "John Doe" factory :user do
sequence(:username) {|n| "user#{n}" } full_name "John Doe"
password "password" sequence(:username) {|n| "user#{n}" }
end password "password"
end end
end
```
Instead of creating a child factory that added additional attributes: Instead of creating a child factory that added additional attributes:
FactoryGirl.define do ```ruby
factory :application_user, :parent => :user do FactoryGirl.define do
full_name { Faker::Name.name } factory :application_user, :parent => :user do
date_of_birth { 21.years.ago } full_name { Faker::Name.name }
gender "Female" date_of_birth { 21.years.ago }
health 90 gender "Female"
end health 90
end end
end
```
You could modify that factory instead. You could modify that factory instead.
FactoryGirl.modify do ```ruby
factory :user do FactoryGirl.modify do
full_name { Faker::Name.name } factory :user do
date_of_birth { 21.years.ago } full_name { Faker::Name.name }
gender "Female" date_of_birth { 21.years.ago }
health 90 gender "Female"
end health 90
end end
end
```
When modifying a factory, you can change any of the attributes you want (aside from callbacks). When modifying a factory, you can change any of the attributes you want (aside from callbacks).
@ -510,20 +578,26 @@ Building or Creating Multiple Records
Sometimes, you'll want to create or build multiple instances of a factory at once. Sometimes, you'll want to create or build multiple instances of a factory at once.
built_users = FactoryGirl.build_list(:user, 25) ```ruby
created_users = FactoryGirl.create_list(:user, 25) built_users = FactoryGirl.build_list(:user, 25)
created_users = FactoryGirl.create_list(:user, 25)
```
These methods will build or create a specific amount of factories and return them as an array. These methods will build or create a specific amount of factories and return them as an array.
To set the attributes for each of the factories, you can pass in a hash as you normally would. To set the attributes for each of the factories, you can pass in a hash as you normally would.
twenty_year_olds = FactoryGirl.build_list(:user, 25, :date_of_birth => 20.years.ago) ```ruby
twenty_year_olds = FactoryGirl.build_list(:user, 25, :date_of_birth => 20.years.ago)
```
Cucumber Integration Cucumber Integration
-------------------- --------------------
factory\_girl ships with step definitions that make calling factories from Cucumber easier. To use them, add the following to features/support/env.rb: factory\_girl ships with step definitions that make calling factories from Cucumber easier. To use them, add the following to features/support/env.rb:
require 'factory_girl/step_definitions' ```ruby
require 'factory_girl/step_definitions'
```
Alternate Syntaxes Alternate Syntaxes
------------------ ------------------
@ -533,15 +607,17 @@ common feature set. Because of this factory\_girl supports "syntax layers" which
provide alternate interfaces. See Factory::Syntax for information about the provide alternate interfaces. See Factory::Syntax for information about the
various layers available. For example, the Machinist-style syntax is popular: various layers available. For example, the Machinist-style syntax is popular:
require 'factory_girl/syntax/blueprint' ```ruby
require 'factory_girl/syntax/make' require 'factory_girl/syntax/blueprint'
require 'factory_girl/syntax/sham' require 'factory_girl/syntax/make'
require 'factory_girl/syntax/sham'
Sham.email {|n| "#{n}@example.com" } Sham.email {|n| "#{n}@example.com" }
User.blueprint do User.blueprint do
name { 'Billy Bob' } name { 'Billy Bob' }
email { Sham.email } email { Sham.email }
end end
User.make(:name => 'Johnny') User.make(:name => 'Johnny')
```