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

Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf203318pmpc
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 

Recently uploaded (20)

Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 

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