SlideShare a Scribd company logo
1 of 25
Tips To Make Your RSpec
Specs Awesome
describe FindReaction do
#Spec 1
it "should return no reaction template when there are no reaction templates" do
post = create :post, locale: "en", type: "basic"
reaction = FindReaction.for(post).reaction
expect(reaction.blank?).to be_true
end
#Spec 2
it "should return no reaction template if reaction templates exist, but non fitting" do
post = create :post, locale: "en", type: "basic"
reaction1 = ReactionTemplate.create locale: "de", subtypes: ["basic", "top_x"]
reaction2 = ReactionTemplate.create locale: "en", subtypes: ["slideshow", "top_x"]
reaction = FindReaction.for(post).reaction
expect(reaction.blank?).to be_true
end
#Spec 3
it "should return the right reaction if it exists" do
post = create :post, locale: "en", type: "basic"
reaction1 = ReactionTemplate.create locale: "en", subtypes: ["basic", "top_x"]
reaction2 = ReactionTemplate.create locale: "en", subtypes: ["basic", "top_x"]
reaction3 = ReactionTemplate.create locale: "en" , subtypes: ["slideshow",
"top_x"]
reaction = FindReaction.for(post).reaction
expect(reaction.blank?).to be_true
expect(reaction).to eq reaction2
end
#Spec 4
it "should change posts reaction_template when attaching it" do
post = create :post, locale: "en", type: "basic"
expect(post.reaction_template.nil?).to be_true
reaction = ReactionTemplate.create locale: "en", subtypes: ["basic", "top_x"]
FindReaction.for(post).attach
expect(post.reaction_template.nil?).to be_false
expect(post.reaction_template).to eq reaction
end
end
 Keep your specs DRY – use before
blocks
 Use before :all instead of before
:each when possible
 Use conditional hooks
• Sometimes if you want to execute some piece of code only
for one example but not for all examples in a context then
you can use conditional hooks.
context "#update" do
before(:each, run: true) do
# do something
end
it "example1", run: :true
it "example2"
end
• Now before(:each) will run only for first example but not
for second example.
 Use build instead of create when
possible
 Use describe to create nested
specs groups. describe should
relate to an operation or an object
 Use variables instead of constants
to keep your specs from becoming
too fragile.
 Use RSpec’s magnificent be_
syntactic sugar
RSpec has many syntactic sugars that makes your specs more readable.
for example:
expect(reaction.blank?).to be_true
When an object reacts to some_method_name? RSpec allows you to write
the test in the following way:
object.should be_some_method_name
Or in our case:
expect(reaction).to be_blank
 Use create! and save! instead of
create and save
 If/When rule of thumb
 Use subject/it clauses to keep your
specs DRY’er and cleaner
result: FindReaction.for(@post).reaction
This can be easily extracted into
subject {FindReaction.for(@post).reaction}
 One assertion per test case
• This way if the spec fails, you immediately
know what went wrong and don’t even have
to look at the detailed output of the failure. It
also keeps your specs clean and focused on
what they’re supposed to test
 Use RSpec’s expect {} block to
describe a change in the state of an
object
RSpec has a nice and clean way to describe these
kind of state changes:
expect { some_operation }.to
change{something}.from(initial_value).to(final_value
)
It is much cleaner and more readable this way.
 Use shared examples.
• When you want to test the same functionality across different subjects, for example different kinds
of users, use shared examples.
context "#edit" do
it "admin should be able to edit his profile"
it "distributor should be able to edit his profile"
End
You can write as
context "#edit" do
shared_examples "profile_editing" do
it "user should be able to edit his profile"
end
context "admin" do
include_examples "profile_editing"
it "should be able see to list of distributors"
end
context "distributor" do
include_examples "profile_editing"
it "should not able to see list of distributors"
end
End
Note - A word of caution – you may lost readability if you use too many shared examples in single file
 Use correct expectations for a spec
 Use the new syntax for object
creation
• Use the new FactoryGirl syntax that is
supported in factory_girl4. This helps the code
be clean
create(:user)
instead of
FactoryGirl.create(:user)
 Use expect and not should syntax
• It’s just nice and clean!
expect(User.all.count).to eq(1)
instead of
User.all.count.should == 1
Note :- Use the Transpec gem helps you to convert
from should syntax to expect syntax
Tagging
# spec/models/commission_spec.rb
describe Commission, commission: true do
# do something
End
rspec –tag commission
Note: We can tag entire context or a single
example in the spec file
describe FindReaction do
before :all do
@post = build :post, locale: "en", type: "basic"
end
before :each do
@post.reaction = nil
end
describe :reaction do
subject { FindReaction.for(@post).reaction }
#Spec 1
context "there are no reaction templates" do
it {expect(subject).to be_blank }
end
#Spec 2
context "reaction templates exist, but non fitting" do
before :each do
reaction1 = ReactionTemplate.create! locale: "de", subtypes: ["basic", "top_x"]
reaction2 = ReactionTemplate.create! locale: "en", subtypes: ["slideshow", "top_x"]
end
it {expect(subject).to be_blank }
end
#Spec 3
context "fitting reaction templates exist" do
before :each do
@reaction1 = ReactionTemplate.create! locale: @post.locale, subtypes: [@post.type, "top_x"]
@reaction2 = ReactionTemplate.create! locale: @post.locale, subtypes: [@post.type, "top_x"]
@reaction3 = ReactionTemplate.create! locale: @post.locale, subtypes: ["slideshow", "top_x"]
end
it {expect(subject).not_to be_blank}
it {expect(subject).to eq @reaction2}
end
end
describe :attach do
#Spec 4
context "attaching a reaction to post" do
before :each do
@reaction = ReactionTemplate.create! locale: @post.locale, subtypes: [@post.type, "top_x"]
end
it "should change posts reaction template" do
expect {
FindReaction.for(@post).attach
}.to change{@post.reaction_template}.from(nil).to(@reaction)
end
end
end
end
CONCLUSION
• Our test-suite runs faster
• Our test file is more readable
• The failure output provided by RSpec is better
• We’re not repeating ourselves between specs
• It is extremely easy to extend the specs to
describe new features
Thank you
Tips to make your rspec specs awesome

More Related Content

Similar to Tips to make your rspec specs awesome

Introduction to unit testing
Introduction to unit testingIntroduction to unit testing
Introduction to unit testingArtem Shoobovych
 
[Pick the date] Class Instructor’s NameWhat Is Autism.docx
[Pick the date]  Class  Instructor’s NameWhat Is Autism.docx[Pick the date]  Class  Instructor’s NameWhat Is Autism.docx
[Pick the date] Class Instructor’s NameWhat Is Autism.docxdanielfoster65629
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsPatchSpace Ltd
 
RSpec: What, How and Why
RSpec: What, How and WhyRSpec: What, How and Why
RSpec: What, How and WhyRatan Sebastian
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Vysakh Sreenivasan
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
OverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docxOverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docxalfred4lewis58146
 
Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7ashhadiqbal
 
asgmt01.classpathasgmt01.project asgmt01 .docx
asgmt01.classpathasgmt01.project  asgmt01  .docxasgmt01.classpathasgmt01.project  asgmt01  .docx
asgmt01.classpathasgmt01.project asgmt01 .docxfredharris32
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
 
Better rspec 進擊的 RSpec
Better rspec 進擊的 RSpecBetter rspec 進擊的 RSpec
Better rspec 進擊的 RSpecLi Hsuan Hung
 

Similar to Tips to make your rspec specs awesome (20)

Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
 
l2-es6-160830040119.pdf
l2-es6-160830040119.pdfl2-es6-160830040119.pdf
l2-es6-160830040119.pdf
 
Introduction to unit testing
Introduction to unit testingIntroduction to unit testing
Introduction to unit testing
 
[Pick the date] Class Instructor’s NameWhat Is Autism.docx
[Pick the date]  Class  Instructor’s NameWhat Is Autism.docx[Pick the date]  Class  Instructor’s NameWhat Is Autism.docx
[Pick the date] Class Instructor’s NameWhat Is Autism.docx
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Rspec
RspecRspec
Rspec
 
RSpec: What, How and Why
RSpec: What, How and WhyRSpec: What, How and Why
RSpec: What, How and Why
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
 
Rspec
RspecRspec
Rspec
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
OverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docxOverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docx
 
Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7
 
Ruby on rails rspec
Ruby on rails rspecRuby on rails rspec
Ruby on rails rspec
 
Rspec 101
Rspec 101Rspec 101
Rspec 101
 
asgmt01.classpathasgmt01.project asgmt01 .docx
asgmt01.classpathasgmt01.project  asgmt01  .docxasgmt01.classpathasgmt01.project  asgmt01  .docx
asgmt01.classpathasgmt01.project asgmt01 .docx
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docx
 
Better rspec 進擊的 RSpec
Better rspec 進擊的 RSpecBetter rspec 進擊的 RSpec
Better rspec 進擊的 RSpec
 

Recently uploaded

UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 

Recently uploaded (20)

UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 

Tips to make your rspec specs awesome

  • 1. Tips To Make Your RSpec Specs Awesome
  • 2. describe FindReaction do #Spec 1 it "should return no reaction template when there are no reaction templates" do post = create :post, locale: "en", type: "basic" reaction = FindReaction.for(post).reaction expect(reaction.blank?).to be_true end #Spec 2 it "should return no reaction template if reaction templates exist, but non fitting" do post = create :post, locale: "en", type: "basic" reaction1 = ReactionTemplate.create locale: "de", subtypes: ["basic", "top_x"] reaction2 = ReactionTemplate.create locale: "en", subtypes: ["slideshow", "top_x"] reaction = FindReaction.for(post).reaction expect(reaction.blank?).to be_true end
  • 3. #Spec 3 it "should return the right reaction if it exists" do post = create :post, locale: "en", type: "basic" reaction1 = ReactionTemplate.create locale: "en", subtypes: ["basic", "top_x"] reaction2 = ReactionTemplate.create locale: "en", subtypes: ["basic", "top_x"] reaction3 = ReactionTemplate.create locale: "en" , subtypes: ["slideshow", "top_x"] reaction = FindReaction.for(post).reaction expect(reaction.blank?).to be_true expect(reaction).to eq reaction2 end #Spec 4 it "should change posts reaction_template when attaching it" do post = create :post, locale: "en", type: "basic" expect(post.reaction_template.nil?).to be_true reaction = ReactionTemplate.create locale: "en", subtypes: ["basic", "top_x"] FindReaction.for(post).attach expect(post.reaction_template.nil?).to be_false expect(post.reaction_template).to eq reaction end end
  • 4.  Keep your specs DRY – use before blocks
  • 5.  Use before :all instead of before :each when possible
  • 6.  Use conditional hooks • Sometimes if you want to execute some piece of code only for one example but not for all examples in a context then you can use conditional hooks. context "#update" do before(:each, run: true) do # do something end it "example1", run: :true it "example2" end • Now before(:each) will run only for first example but not for second example.
  • 7.  Use build instead of create when possible
  • 8.  Use describe to create nested specs groups. describe should relate to an operation or an object
  • 9.  Use variables instead of constants to keep your specs from becoming too fragile.
  • 10.  Use RSpec’s magnificent be_ syntactic sugar RSpec has many syntactic sugars that makes your specs more readable. for example: expect(reaction.blank?).to be_true When an object reacts to some_method_name? RSpec allows you to write the test in the following way: object.should be_some_method_name Or in our case: expect(reaction).to be_blank
  • 11.  Use create! and save! instead of create and save
  • 12.  If/When rule of thumb
  • 13.  Use subject/it clauses to keep your specs DRY’er and cleaner result: FindReaction.for(@post).reaction This can be easily extracted into subject {FindReaction.for(@post).reaction}
  • 14.  One assertion per test case • This way if the spec fails, you immediately know what went wrong and don’t even have to look at the detailed output of the failure. It also keeps your specs clean and focused on what they’re supposed to test
  • 15.  Use RSpec’s expect {} block to describe a change in the state of an object RSpec has a nice and clean way to describe these kind of state changes: expect { some_operation }.to change{something}.from(initial_value).to(final_value ) It is much cleaner and more readable this way.
  • 16.  Use shared examples. • When you want to test the same functionality across different subjects, for example different kinds of users, use shared examples. context "#edit" do it "admin should be able to edit his profile" it "distributor should be able to edit his profile" End You can write as context "#edit" do shared_examples "profile_editing" do it "user should be able to edit his profile" end context "admin" do include_examples "profile_editing" it "should be able see to list of distributors" end context "distributor" do include_examples "profile_editing" it "should not able to see list of distributors" end End Note - A word of caution – you may lost readability if you use too many shared examples in single file
  • 17.  Use correct expectations for a spec
  • 18.  Use the new syntax for object creation • Use the new FactoryGirl syntax that is supported in factory_girl4. This helps the code be clean create(:user) instead of FactoryGirl.create(:user)
  • 19.  Use expect and not should syntax • It’s just nice and clean! expect(User.all.count).to eq(1) instead of User.all.count.should == 1 Note :- Use the Transpec gem helps you to convert from should syntax to expect syntax
  • 20. Tagging # spec/models/commission_spec.rb describe Commission, commission: true do # do something End rspec –tag commission Note: We can tag entire context or a single example in the spec file
  • 21. describe FindReaction do before :all do @post = build :post, locale: "en", type: "basic" end before :each do @post.reaction = nil end describe :reaction do subject { FindReaction.for(@post).reaction } #Spec 1 context "there are no reaction templates" do it {expect(subject).to be_blank } end #Spec 2 context "reaction templates exist, but non fitting" do before :each do reaction1 = ReactionTemplate.create! locale: "de", subtypes: ["basic", "top_x"] reaction2 = ReactionTemplate.create! locale: "en", subtypes: ["slideshow", "top_x"] end it {expect(subject).to be_blank } end
  • 22. #Spec 3 context "fitting reaction templates exist" do before :each do @reaction1 = ReactionTemplate.create! locale: @post.locale, subtypes: [@post.type, "top_x"] @reaction2 = ReactionTemplate.create! locale: @post.locale, subtypes: [@post.type, "top_x"] @reaction3 = ReactionTemplate.create! locale: @post.locale, subtypes: ["slideshow", "top_x"] end it {expect(subject).not_to be_blank} it {expect(subject).to eq @reaction2} end end describe :attach do #Spec 4 context "attaching a reaction to post" do before :each do @reaction = ReactionTemplate.create! locale: @post.locale, subtypes: [@post.type, "top_x"] end it "should change posts reaction template" do expect { FindReaction.for(@post).attach }.to change{@post.reaction_template}.from(nil).to(@reaction) end end end end
  • 23. CONCLUSION • Our test-suite runs faster • Our test file is more readable • The failure output provided by RSpec is better • We’re not repeating ourselves between specs • It is extremely easy to extend the specs to describe new features