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`:
```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`:
```ruby
gem "factory_girl", "~> 2.1.0"
```
Once your Gemfile is updated, you'll want to update your bundle.
@ -19,6 +23,7 @@ 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:
```ruby
# This will guess the User class
FactoryGirl.define do
factory :user do
@ -41,6 +46,7 @@ Each factory has a name and a set of attributes. The name is used to guess the c
admin true
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.
@ -59,6 +65,7 @@ Using factories
factory\_girl supports several different build strategies: build, create, attributes\_for and stub:
```ruby
# Returns a User instance that's not saved
user = FactoryGirl.build(:user)
@ -75,16 +82,20 @@ factory\_girl supports several different build strategies: build, create, attrib
FactoryGirl.create(:user) do |user|
user.posts.create(attributes_for(:post))
end
```
No matter which strategy is used, it's possible to override the defined attributes by passing a hash:
```ruby
# Build a User instance and override the first_name property
user = FactoryGirl.build(:user, :first_name => 'Joe')
user.first_name
# => "Joe"
```
If repeating "FactoryGirl" is too verbose for you, you can mix the syntax methods in:
```ruby
# rspec
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
@ -94,14 +105,17 @@ If repeating "FactoryGirl" is too verbose for you, you can mix the syntax method
class Test::Unit::TestCase
include Factory::Syntax::Methods
end
```
This would allow you to write:
```ruby
describe User, "#full_name" do
subject { create(:user, :first_name => "John", :last_name => "Doe") }
its(:full_name) { should == "John Doe" }
end
```
Lazy Attributes
---------------
@ -112,17 +126,20 @@ 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:
```ruby
factory :user do
# ...
activation_code { User.generate_activation_code }
date_of_birth { 21.years.ago }
end
```
Aliases
-------
Aliases allow you to use named associations more easily.
```ruby
factory :user, :aliases => [:author, :commenter] do
first_name "John"
last_name "Doe"
@ -143,12 +160,14 @@ Aliases allow you to use named associations more easily.
# association :commenter, :factory => :user
body "Great article!"
end
```
Dependent Attributes
--------------------
Attributes can be based on the values of other attributes using the proxy that is yielded to lazy attribute blocks:
```ruby
factory :user do
first_name 'Joe'
last_name 'Blow'
@ -157,12 +176,14 @@ Attributes can be based on the values of other attributes using the proxy that i
FactoryGirl.create(:user, :last_name => 'Doe').email
# => "joe.doe@example.com"
```
Transient Attributes
--------------------
There may be times where your code can be DRYed up by passing in transient attributes to factories.
```ruby
factory :user do
ignore do
rockstar true
@ -179,6 +200,7 @@ There may be times where your code can be DRYed up by passing in transient attri
FactoryGirl.create(:user, :upcased => true).name
#=> "JOHN DOE - ROCKSTAR"
```
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
@ -194,20 +216,25 @@ 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.
```ruby
factory :post do
# ...
author
end
```
You can also specify a different factory or override attributes:
```ruby
factory :post do
# ...
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.
```ruby
# Builds and saves a User and a Post
post = FactoryGirl.create(:post)
post.new_record? # => false
@ -217,9 +244,11 @@ The behavior of the association method varies depending on the build strategy us
post = FactoryGirl.build(:post)
post.new_record? # => true
post.author.new_record? # => false
```
To not save the associated object, specify :method => :build in the factory:
```ruby
factory :post do
# ...
association :author, :factory => :user, :method => :build
@ -229,12 +258,14 @@ To not save the associated object, specify :method => :build in the factory:
post = FactoryGirl.build(:post)
post.new_record? # => true
post.author.new_record? # => true
```
Inheritance
-----------
You can easily create multiple factories for the same class without repeating common attributes by nesting factories:
```ruby
factory :post do
title 'A title'
@ -246,9 +277,11 @@ You can easily create multiple factories for the same class without repeating co
approved_post = FactoryGirl.create(:approved_post)
approved_post.title # => 'A title'
approved_post.approved # => true
```
You can also assign the parent explicitly:
```ruby
factory :post do
title 'A title'
end
@ -256,6 +289,7 @@ You can also assign the parent explicitly:
factory :approved_post, :parent => :post do
approved true
end
```
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
@ -270,6 +304,7 @@ generated using sequences. Sequences are defined by calling sequence in a
definition block, and values in a sequence are generated by calling
FactoryGirl.generate:
```ruby
# Defines a new sequence
FactoryGirl.define do
sequence :email do |n|
@ -282,37 +317,48 @@ FactoryGirl.generate:
FactoryGirl.generate :email
# => "person2@example.com"
```
Sequences can be used as attributes:
```ruby
factory :user do
email
end
```
Or in lazy attributes:
```ruby
factory :invite do
invitee { FactoryGirl.generate(:email) }
end
```
And it's also possible to define an in-line sequence that is only used in
a particular factory:
```ruby
factory :user do
sequence(:email) {|n| "person#{n}@example.com" }
end
```
You can also override the initial value:
```ruby
factory :user do
sequence(:email, 1000) {|n| "person#{n}@example.com" }
end
```
Without a block, the value will increment itself, starting at its initial value:
```ruby
factory :post do
sequence(:position)
end
```
Traits
------
@ -320,6 +366,7 @@ Traits
Traits allow you to group attributes together and then apply them
to any factory.
```ruby
factory :user, :aliases => [:author]
factory :story do
@ -349,18 +396,22 @@ to any factory.
factory :week_long_unpublished_story, :traits => [:unpublished, :week_long_publishing]
factory :month_long_unpublished_story, :traits => [:unpublished, :month_long_publishing]
end
```
Traits can be used as attributes:
```ruby
factory :week_long_published_story_with_title, :parent => :story do
published
week_long_publishing
title { "Publishing that was started at {start_at}" }
end
```
Traits that define the same attributes won't raise AttributeDefinitionErrors;
the trait that defines the attribute latest gets precedence.
```ruby
factory :user do
name "Friendly User"
login { name }
@ -385,9 +436,11 @@ the trait that defines the attribute latest gets precedence.
factory :male_admin, :traits => [:male, :admin] # login will be "admin-John Doe"
factory :female_admin, :traits => [:admin, :female] # login will be "Jane Doe (F)"
end
```
You can also override individual attributes granted by a trait in subclasses.
```ruby
factory :user do
name "Friendly User"
login { name }
@ -403,9 +456,11 @@ You can also override individual attributes granted by a trait in subclasses.
name "Brandon"
end
end
```
Traits can also be passed in as a list of symbols when you construct an instance from FactoryGirl.
```ruby
factory :user do
name "Friendly User"
@ -421,6 +476,7 @@ Traits can also be passed in as a list of symbols when you construct an instance
# creates an admin user with gender "Male" and name "Jon Snow"
FactoryGirl.create(:user, :admin, :male, :name => "Jon Snow")
```
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:
```ruby
# Define a factory that calls the generate_hashed_password method after it is built
factory :user do
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.
You can also define multiple types of callbacks on the same factory:
```ruby
factory :user do
after_build { |user| do_something_to(user) }
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:
```ruby
factory :user do
after_create { this_runs_first }
after_create { then_this }
end
```
Calling FactoryGirl.create will invoke both after\_build and after\_create callbacks.
@ -468,6 +530,7 @@ modify that factory instead of creating a child factory and adding attributes th
If a gem were to give you a User factory:
```ruby
FactoryGirl.define do
factory :user do
full_name "John Doe"
@ -475,9 +538,11 @@ If a gem were to give you a User factory:
password "password"
end
end
```
Instead of creating a child factory that added additional attributes:
```ruby
FactoryGirl.define do
factory :application_user, :parent => :user do
full_name { Faker::Name.name }
@ -486,9 +551,11 @@ Instead of creating a child factory that added additional attributes:
health 90
end
end
```
You could modify that factory instead.
```ruby
FactoryGirl.modify do
factory :user do
full_name { Faker::Name.name }
@ -497,6 +564,7 @@ You could modify that factory instead.
health 90
end
end
```
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.
```ruby
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.
To set the attributes for each of the factories, you can pass in a hash as you normally would.
```ruby
twenty_year_olds = FactoryGirl.build_list(:user, 25, :date_of_birth => 20.years.ago)
```
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:
```ruby
require 'factory_girl/step_definitions'
```
Alternate Syntaxes
------------------
@ -533,6 +607,7 @@ 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. For example, the Machinist-style syntax is popular:
```ruby
require 'factory_girl/syntax/blueprint'
require 'factory_girl/syntax/make'
require 'factory_girl/syntax/sham'
@ -545,3 +620,4 @@ various layers available. For example, the Machinist-style syntax is popular:
end
User.make(:name => 'Johnny')
```