SlideShare a Scribd company logo
factory_girl
# RSpec
# spec/support/factory_girl.rb
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
If you do not include FactoryGirl::Syntax::Methods in your test suite, then all
factory_girl methods will need to be prefaced with FactoryGirl.
● One factory for each class that provides the simplest set of attributes
necessary to create an instance of that class
● 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.
● Attempting to define multiple factories with the same name will raise an
error.
# This will guess the User class
FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
admin false
end
# This will use the User class (Admin would have been guessed)
factory :admin, class: User do
first_name "Admin"
last_name "User"
admin true
end
end
Using Factories
user = build(:user) # Returns a User instance that's not saved
user = create(:user) # Returns a saved User instance
user = build(:user, first_name: "Joe") # Build a User instance and override the
first_name property
# Returns a hash of attributes that can be used to build a User instance
attrs = attributes_for(:user)
# Returns an object with all defined attributes stubbed out
stub = build_stubbed(:user)
# Passing a block to any of the methods above will yield the return object
create(:user) do |user|
user.posts.create(attributes_for(:post))
end
Lazy Attributes
● factory attributes can be added using static values that are evaluated when
the factory is defined.
● Some attributes 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 :user do
# ...
activation_code { User.generate_activation_code }
date_of_birth { 21.years.ago }
end
Aliases
factory :user, aliases: [:author, :commenter] do
first_name "John"
last_name "Doe"
end
factory :post do
author
# instead of
# association :author, factory: :user
title "How to read a book effectively"
end
# Post Model
class Post
belongs_to :author, class: User
end
Dependent Attributes
Attributes can be based on the values of other attributes using the evaluator that
is yielded to lazy attribute blocks:
factory :user do
first_name "Joe"
last_name "Blow"
email { "#{first_name}.#{last_name}@example.com".downcase }
end
create(:user, last_name: "Doe").email
# => "joe.doe@example.com"
Inheritance
You can easily create multiple factories for the same class without repeating
common attributes by nesting factories.
factory :post do
title "A title"
factory :approved_post do
approved true
end
end
create(:approved_post)
factory :post do
title "A title"
end
factory :approved_post, parent: :post do
approved true
end
● It's good practice to define a basic factory for each class with only the
attributes required to create it.
● Create more specific factories that inherit from this basic parent.
● Factory definitions are still code, so keep them DRY.
Sequences
● Unique values in a specific format can be generated using sequences.
● Sequences are defined by calling sequence in a definition block, and values in
a sequence are generated by calling generate.
# Defines a new sequence
FactoryGirl.define do
sequence :email do |n|
"person#{n}@example.com"
end
end
generate :email
➢ Sequences can be used as attributes:
factory :user do
email
end
➢ Or in lazy attributes:
factory :invite do
invitee { generate(:email) }
end
Building or Creating Multiple Records
● create or build multiple instances of a factory at once.
built_users = build_list(:user, 25)
built_users = build_stubbed_list(:user, 25)
created_users = create_list(:user, 25, date_of_birth: 12.years.ago)
● These methods will build or create a specific amount of factories and return
them as an array.
● There's also a set of *_pair methods for creating two records at a time:
built_users = build_pair(:user) # array of two built users
created_users = create_pair(:user) # array of two created users
Callbacks
● after(:build) - called after a factory is built (via FactoryGirl.build,
FactoryGirl.create)
● before(:create) - called before a factory is saved (via FactoryGirl.create)
● after(:create) - called after a factory is saved (via FactoryGirl.create)
● after(:stub) - called after a factory is stubbed (via FactoryGirl.build_stubbed)
# Define a factory that calls the generate_hashed_password method after it is built
factory :user do
after(:build) { |user| generate_hashed_password(user) }
● you'll have an instance of the user in the block.
● You can also define multiple types of callbacks on the same factory
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:
● Calling create will invoke both after_build and after_create callbacks.
● Child factories will inherit (and can also define) callbacks from their parent factory.
Transient Attributes
factory :user do
transient do
rockstar true
upcased false
end
name { "John Doe#{" - Rockstar" if rockstar}" }
after(:create) do |user, evaluator|
user.name.upcase! if evaluator.upcased
end
end
create(:user, upcased: true).name
#=> "JOHN DOE - ROCKSTAR"
● Static and dynamic attributes can be created as transient attributes.
● Transient attributes will be ignored within attributes_for.
● Within factory_girl's dynamic attributes, you can access transient attributes as
you would expect.
● If you need to access the evaluator in a factory_girl callback,
you'll need to declare a second block argument (for the evaluator)
and access transient attributes from there.
Traits
● Traits allow you to group attributes together and then apply them to any
factory.
● Traits can be used as attributes:
● Traits that define the same attributes won't raise AttributeDefinitionErrors;
the trait that defines the attribute latest gets precedence.
● You can also override individual attributes granted by a trait in subclasses.
● Traits can also be passed in as a list of symbols when you construct an
instance from factory_girl.
● Traits can be used with associations easily too:
● Traits can be used within other traits to mix in their attributes.
factory :user do
name "Friendly User"
login { name }
trait :admin do
is_admin true
login { "#{name} (Admin)" }
end
end
factory :male_admin, factory: :user do
admin
gender “Male”
end
factory :post do
association :author, :admin, factory: :user, name: 'John Doe'
end
Wrapping up...
● FactoryGirl is Magic
● Easier to maintain
● Less of Headache
● Fun to work with
References..
http://robots.thoughtbot.com/use-factory-girls-build-stubbed-for-a-faster-test
http://www.agileventures.org/articles/testing-with-rspec-stubs-mocks-factories-
what-to-choose
https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.m
d
part 1: http://cookieshq.co.uk/posts/useful-factory-girl-methods/
part 2: http://cookieshq.co.uk/posts/useful-factory-girl-methods-part-two/
Factory girl

More Related Content

What's hot

Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
Advanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringAdvanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringBurt Beckwith
 
Developing components and extensions for ext js
Developing components and extensions for ext jsDeveloping components and extensions for ext js
Developing components and extensions for ext jsMats Bryntse
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 
Grain final border one
Grain final border oneGrain final border one
Grain final border oneAshish Gupta
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript TestingThomas Fuchs
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.jsMatthew Beale
 
Academy PRO: React native - navigation
Academy PRO: React native - navigationAcademy PRO: React native - navigation
Academy PRO: React native - navigationBinary Studio
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
Cocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollersCocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollersStijn Willems
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript Glenn Stovall
 
Ember and containers
Ember and containersEmber and containers
Ember and containersMatthew Beale
 
Hello, React Hooks!
Hello, React Hooks!Hello, React Hooks!
Hello, React Hooks!Heejong Ahn
 

What's hot (20)

Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
Advanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringAdvanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and Monitoring
 
Developing components and extensions for ext js
Developing components and extensions for ext jsDeveloping components and extensions for ext js
Developing components and extensions for ext js
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
Grain final border one
Grain final border oneGrain final border one
Grain final border one
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript Testing
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 
Academy PRO: React native - navigation
Academy PRO: React native - navigationAcademy PRO: React native - navigation
Academy PRO: React native - navigation
 
PL/SQL Unit Testing Can Be Fun!
PL/SQL Unit Testing Can Be Fun!PL/SQL Unit Testing Can Be Fun!
PL/SQL Unit Testing Can Be Fun!
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
Cocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollersCocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollers
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Ember and containers
Ember and containersEmber and containers
Ember and containers
 
Hello, React Hooks!
Hello, React Hooks!Hello, React Hooks!
Hello, React Hooks!
 

Similar to Factory girl

CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Fixture Replacement Plugins
Fixture Replacement PluginsFixture Replacement Plugins
Fixture Replacement PluginsPaul Klipp
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdffashionscollect
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongVu Huy
 
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongTechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongGrokking VN
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking introHans Jones
 
Improving your Gradle builds
Improving your Gradle buildsImproving your Gradle builds
Improving your Gradle buildsPeter Ledbrook
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 

Similar to Factory girl (20)

CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Fixture Replacement Plugins
Fixture Replacement PluginsFixture Replacement Plugins
Fixture Replacement Plugins
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
 
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongTechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
Improving your Gradle builds
Improving your Gradle buildsImproving your Gradle builds
Improving your Gradle builds
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 

Recently uploaded

Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdfAhmedHussein950959
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdfKamal Acharya
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdfKamal Acharya
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf884710SadaqatAli
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdfKamal Acharya
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfPipe Restoration Solutions
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxVishalDeshpande27
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptssuser9bd3ba
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...Amil baba
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfAbrahamGadissa
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopEmre Günaydın
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdfKamal Acharya
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationRobbie Edward Sayers
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxMd. Shahidul Islam Prodhan
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsAtif Razi
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234AafreenAbuthahir2
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
 

Recently uploaded (20)

Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 

Factory girl

  • 2. # RSpec # spec/support/factory_girl.rb RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end If you do not include FactoryGirl::Syntax::Methods in your test suite, then all factory_girl methods will need to be prefaced with FactoryGirl.
  • 3. ● One factory for each class that provides the simplest set of attributes necessary to create an instance of that class ● 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. ● Attempting to define multiple factories with the same name will raise an error.
  • 4. # This will guess the User class FactoryGirl.define do factory :user do first_name "John" last_name "Doe" admin false end # This will use the User class (Admin would have been guessed) factory :admin, class: User do first_name "Admin" last_name "User" admin true end end
  • 5. Using Factories user = build(:user) # Returns a User instance that's not saved user = create(:user) # Returns a saved User instance user = build(:user, first_name: "Joe") # Build a User instance and override the first_name property # Returns a hash of attributes that can be used to build a User instance attrs = attributes_for(:user) # Returns an object with all defined attributes stubbed out stub = build_stubbed(:user) # Passing a block to any of the methods above will yield the return object create(:user) do |user| user.posts.create(attributes_for(:post)) end
  • 6. Lazy Attributes ● factory attributes can be added using static values that are evaluated when the factory is defined. ● Some attributes 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 :user do # ... activation_code { User.generate_activation_code } date_of_birth { 21.years.ago } end
  • 7. Aliases factory :user, aliases: [:author, :commenter] do first_name "John" last_name "Doe" end factory :post do author # instead of # association :author, factory: :user title "How to read a book effectively" end # Post Model class Post belongs_to :author, class: User end
  • 8. Dependent Attributes Attributes can be based on the values of other attributes using the evaluator that is yielded to lazy attribute blocks: factory :user do first_name "Joe" last_name "Blow" email { "#{first_name}.#{last_name}@example.com".downcase } end create(:user, last_name: "Doe").email # => "joe.doe@example.com"
  • 9. Inheritance You can easily create multiple factories for the same class without repeating common attributes by nesting factories. factory :post do title "A title" factory :approved_post do approved true end end create(:approved_post) factory :post do title "A title" end factory :approved_post, parent: :post do approved true end
  • 10. ● It's good practice to define a basic factory for each class with only the attributes required to create it. ● Create more specific factories that inherit from this basic parent. ● Factory definitions are still code, so keep them DRY.
  • 11. Sequences ● Unique values in a specific format can be generated using sequences. ● Sequences are defined by calling sequence in a definition block, and values in a sequence are generated by calling generate. # Defines a new sequence FactoryGirl.define do sequence :email do |n| "person#{n}@example.com" end end generate :email ➢ Sequences can be used as attributes: factory :user do email end ➢ Or in lazy attributes: factory :invite do invitee { generate(:email) } end
  • 12. Building or Creating Multiple Records ● create or build multiple instances of a factory at once. built_users = build_list(:user, 25) built_users = build_stubbed_list(:user, 25) created_users = create_list(:user, 25, date_of_birth: 12.years.ago) ● These methods will build or create a specific amount of factories and return them as an array. ● There's also a set of *_pair methods for creating two records at a time: built_users = build_pair(:user) # array of two built users created_users = create_pair(:user) # array of two created users
  • 13. Callbacks ● after(:build) - called after a factory is built (via FactoryGirl.build, FactoryGirl.create) ● before(:create) - called before a factory is saved (via FactoryGirl.create) ● after(:create) - called after a factory is saved (via FactoryGirl.create) ● after(:stub) - called after a factory is stubbed (via FactoryGirl.build_stubbed) # Define a factory that calls the generate_hashed_password method after it is built factory :user do after(:build) { |user| generate_hashed_password(user) }
  • 14. ● you'll have an instance of the user in the block. ● You can also define multiple types of callbacks on the same factory 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: ● Calling create will invoke both after_build and after_create callbacks. ● Child factories will inherit (and can also define) callbacks from their parent factory.
  • 15. Transient Attributes factory :user do transient do rockstar true upcased false end name { "John Doe#{" - Rockstar" if rockstar}" } after(:create) do |user, evaluator| user.name.upcase! if evaluator.upcased end end create(:user, upcased: true).name #=> "JOHN DOE - ROCKSTAR"
  • 16. ● Static and dynamic attributes can be created as transient attributes. ● Transient attributes will be ignored within attributes_for. ● Within factory_girl's dynamic attributes, you can access transient attributes as you would expect. ● If you need to access the evaluator in a factory_girl callback, you'll need to declare a second block argument (for the evaluator) and access transient attributes from there.
  • 17. Traits ● Traits allow you to group attributes together and then apply them to any factory. ● Traits can be used as attributes: ● Traits that define the same attributes won't raise AttributeDefinitionErrors; the trait that defines the attribute latest gets precedence. ● You can also override individual attributes granted by a trait in subclasses. ● Traits can also be passed in as a list of symbols when you construct an instance from factory_girl. ● Traits can be used with associations easily too: ● Traits can be used within other traits to mix in their attributes.
  • 18. factory :user do name "Friendly User" login { name } trait :admin do is_admin true login { "#{name} (Admin)" } end end factory :male_admin, factory: :user do admin gender “Male” end factory :post do association :author, :admin, factory: :user, name: 'John Doe' end
  • 19. Wrapping up... ● FactoryGirl is Magic ● Easier to maintain ● Less of Headache ● Fun to work with