SlideShare a Scribd company logo
Rspec 101Jason Noblehttp://jasonnoble.org
Example Groupdescribe()Defines example group of testsString we pass describes the item we’re testingit()Defines a code exampleString we pass describes the specific behaviour
describe() Methoddescribe “A User” {…}A Userdescribe User {…}Userdescribe User, “with no roles assigned” {…}User with no roles assigned
Describe blocks can be nested
context() methodcontext() is an alias for describe()Use describe() for things, context() for context
it() methodArgument should state what is being tested
Pending testsWe can mark tests to be implemented “later”
Pending tests (cont.)Each method of marking a test as pending has its usefulness:Add pending examples as you think of stuff to testDisable failing examples without losing track that you need to fix those at some pointWrap failing examples when you want to be notified when changes to the system cause them to pass (bug is fixed, etc)
before()/after() methodBefore/after methods helps you set and/or reset initial stateCreate a new stack, add one element to itTakes one argument:eachExecutes this block before each test group executes:allExecutes this block once for all tests before the first test is run
before(:each) method
before(:all)Method is run once and only once for a group of testsBe careful using this method, usually we want each test to have it’s own environment setupSharing state between examples can cause unexpected thingsGood examples:Opening a network connectionPre-seeding caches
after(:each) methodCode is ran after each exampleRarely necessary because each example runs in its own scope, and consequently the instance variables in that scope are resetCan be useful to reset global state of things after your test completesafter(:each) is guaranteed to run after each example, even if failure or errors are raised
after(:each) example
after(:all) methodThis is even more rare than the after(:each)Examples:Close down browsersClose database connectionsClose socketsAny resource we want to release when we’re done, but not after every individual test
around(:each) methodSupports APIs that require a blockVery rarely, if ever usedI have never used thisPut your functionality into before/after blocks if at all possibleSee http://relishapp.com/rspec/rspec-core/v/2-0/dir/hooks/around-hooks if you’re interested
Helper MethodsDefined within an example groupAvailable to all examples in the group
Shared Helper MethodsIf helper methods need to be used across example groups, put them in one or more modules and include modules in example groups we want to have access
Shared ExamplesIf we expect instances of more than one class to behave in the same way, a shared example group describes the behavior once and includes it in multiple example groups
Shared examples (cont.)
RSpec::ExpectationsOne goal of BDD is getting the words rightExpectations vs. AssertionsWe are setting an expectation of what should happen rather than what will happenIn fact the word should is part of RSpecresult.should equal(5)message.should match(/on Sunday/)
should, should_not and matchersresult.should equal(5)If result is equal to 5, it passesresult.should_not equal(5)If result is anything other than 5, it passesGeneral Pattern:result.should   ________(value)_______ is a matcher
RSpec built in Matchersinclude(item)prime_numbers.should_not include(8)respond_to(message)list.shouldrespond_to(:length)raise_error(type)lambda { Object.new.explode! }.should raise_error(NameError)
4 ways to be equala == bValue equality (Most common)a === bIs Object a the same Object as ba.eql?(b)Are a and b values equal and of same typea.equal?(b)Is Object a the same Object as b(General Rule: The longer the method name, the more restrictive the matcher is)
Do not use != in expectationsactual.should != expectedaction.should_not == expectedCauses issues, explained in detail in the RSpec book
Floating Point Calculations“expected 5.25 got 5.251” is frustrating in a failure messageRSpec offers a be_close matcher that accepts an expected value and an acceptable deltaresult.shouldbe_close(5.25, 0.005)Will pass as long as result is within .005 of 5.25
Matching Textresponse.should match(/this expression/)Matches if response has text “this expression” somewhere in its contentsresponse.should =~ /this expression/Functionally equivalent to the previous one
Expect{}Tests that a block of code causes some effectYou can also use .to(1) or .from(0).to(1)
Predicate MatchersHow do we test array.empty?array.empty?.should == truearray.shouldbe_empty
Predicate matchers (cont.)RSpec gives you other optionsbe_be_ated.shouldbe_a_kind_of(Player)  => ted.kind_of?(Player)be_anted.shouldbe_an_instance_of(Player) =>ted.instance_of?(Player)RSpec also lets you write your own matchers
Matchershave_ becomes has_request_params.shouldhave_key(:id) =>request_params.has_key?(:id).should == true
specify{}Sometimes RSpec can guess your testsit “should have 32 pieces” do	@board.should have(32).piecesendspecify { @board.should have(32).pieces }This is used rarely (very simple tests)
subject {}Clean up your tests by specifying a subject
RSpec MocksMocks allow you to fake functionality that isn’t being tested.  See the book for more info.
rspec commandrspec –helpList options available to running RSpecrspec spec/simple_math_spec.rbRun only one spec filerspec specRun all specs in spec/ directoryrspec spec --format documentationMakes RSpec more verbose with test output
rspec commands (cont.)rspec spec –colorPassing is green, pending is yellow, fail is redStore common options in .rspec file--color--format documentationOptions stored in ./.rspec take precedence over ~/.rspec, options declared command line win
Let’s get startedmkdir -p calculator/{lib,spec}cd calculatormate .
spec/calculator_spec.rblib/calculator.rb
spec/calculator_spec.rb

More Related Content

PPTX
RSpec: What, How and Why
PDF
RSpec 3: The new, the old, the good
PDF
Testing Ruby with Rspec (a beginner's guide)
PPTX
Rspec presentation
PDF
Factory Girl
PPT
Ruby on Rails testing with Rspec
PPT
TDD, BDD, RSpec
PPTX
Clean Code
RSpec: What, How and Why
RSpec 3: The new, the old, the good
Testing Ruby with Rspec (a beginner's guide)
Rspec presentation
Factory Girl
Ruby on Rails testing with Rspec
TDD, BDD, RSpec
Clean Code

What's hot (20)

KEY
How To Test Everything
PDF
Intro to Unit Testing in AngularJS
PDF
Test-Driven Development of AngularJS Applications
PDF
Describe's Full of It's
PDF
Rspec API Documentation
PDF
Ruby on rails rspec
PPT
Test driven development_for_php
PPT
Perl Tidy Perl Critic
PDF
Introduction to Python decorators
PPTX
Test in action week 4
PPTX
Unit testing of java script and angularjs application using Karma Jasmine Fra...
PDF
TDD, BDD and mocks
PPTX
Test in action – week 1
PPT
Behaviour-Driven Development
PDF
TDD with PhpSpec
PDF
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
PDF
Effective Java with Groovy - How Language Influences Adoption of Good Practices
PDF
Unit Testing in SilverStripe
PPTX
PDF
Testing Legacy Rails Apps
How To Test Everything
Intro to Unit Testing in AngularJS
Test-Driven Development of AngularJS Applications
Describe's Full of It's
Rspec API Documentation
Ruby on rails rspec
Test driven development_for_php
Perl Tidy Perl Critic
Introduction to Python decorators
Test in action week 4
Unit testing of java script and angularjs application using Karma Jasmine Fra...
TDD, BDD and mocks
Test in action – week 1
Behaviour-Driven Development
TDD with PhpSpec
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Unit Testing in SilverStripe
Testing Legacy Rails Apps
Ad

Viewers also liked (12)

PDF
Testing with Rspec 3
PDF
MacRuby
PDF
Basic RSpec 2
PDF
Monitoring web application behaviour with cucumber-nagios
PDF
Automated testing with RSpec
PPTX
Serverspec and Sensu - Testing and Monitoring collide
PPTX
Behavior driven development - cucumber, Junit and java
PDF
Behavior Driven Development with Cucumber
PDF
RSpec on Rails Tutorial
PDF
Introduction to BDD with Cucumber for Java
PDF
Behavior Driven Development with Cucumber
PDF
RSpec 2 Best practices
Testing with Rspec 3
MacRuby
Basic RSpec 2
Monitoring web application behaviour with cucumber-nagios
Automated testing with RSpec
Serverspec and Sensu - Testing and Monitoring collide
Behavior driven development - cucumber, Junit and java
Behavior Driven Development with Cucumber
RSpec on Rails Tutorial
Introduction to BDD with Cucumber for Java
Behavior Driven Development with Cucumber
RSpec 2 Best practices
Ad

Similar to Rspec 101 (20)

PDF
R spec let there be tests
PDF
RSpec Quick Reference
PDF
Introduction to unit testing
PDF
Rspec tutorial
ZIP
Rspec Tips
PDF
PDF
BDD style Unit Testing
KEY
Uses & Abuses of Mocks & Stubs
PDF
RSpec 3.0: Under the Covers
PDF
Rspec basics
KEY
Tdd for BT E2E test community
PDF
PDF
PDF
RSpec best practice - avoid using before and let
PDF
2011-02-03 LA RubyConf Rails3 TDD Workshop
PDF
Fog City Ruby - Triple Equals Black Magic with speaker notes
PPTX
TDD with RSpec
PDF
Ruby Programming Introduction
KEY
Intro to Ruby (and RSpec)
R spec let there be tests
RSpec Quick Reference
Introduction to unit testing
Rspec tutorial
Rspec Tips
BDD style Unit Testing
Uses & Abuses of Mocks & Stubs
RSpec 3.0: Under the Covers
Rspec basics
Tdd for BT E2E test community
RSpec best practice - avoid using before and let
2011-02-03 LA RubyConf Rails3 TDD Workshop
Fog City Ruby - Triple Equals Black Magic with speaker notes
TDD with RSpec
Ruby Programming Introduction
Intro to Ruby (and RSpec)

More from Jason Noble (17)

PPTX
Intro to TDD and BDD
PPTX
Davinci git brown_bag
PPTX
Dash of ajax
PPT
jQuery Intro
PPTX
Intro to Rails Give Camp Atlanta
PPTX
Google apps
PPTX
Smarter cart
PPTX
Cart creation-101217222728-phpapp01
PPTX
Catalog display
PPTX
Validation unit testing
PPT
Creating the application
PPT
Capistrano
PPT
Atlanta Pm Git 101
PPT
Regex Intro
PPT
Git101
PPT
Git Atlrug
PPT
Git102
Intro to TDD and BDD
Davinci git brown_bag
Dash of ajax
jQuery Intro
Intro to Rails Give Camp Atlanta
Google apps
Smarter cart
Cart creation-101217222728-phpapp01
Catalog display
Validation unit testing
Creating the application
Capistrano
Atlanta Pm Git 101
Regex Intro
Git101
Git Atlrug
Git102

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
KodekX | Application Modernization Development
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Machine learning based COVID-19 study performance prediction
PDF
Electronic commerce courselecture one. Pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Cloud computing and distributed systems.
PDF
cuic standard and advanced reporting.pdf
Unlocking AI with Model Context Protocol (MCP)
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
Spectral efficient network and resource selection model in 5G networks
Mobile App Security Testing_ A Comprehensive Guide.pdf
Network Security Unit 5.pdf for BCA BBA.
The AUB Centre for AI in Media Proposal.docx
Per capita expenditure prediction using model stacking based on satellite ima...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Machine learning based COVID-19 study performance prediction
Electronic commerce courselecture one. Pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation_ Review paper, used for researhc scholars
Understanding_Digital_Forensics_Presentation.pptx
sap open course for s4hana steps from ECC to s4
Cloud computing and distributed systems.
cuic standard and advanced reporting.pdf

Rspec 101

  • 2. Example Groupdescribe()Defines example group of testsString we pass describes the item we’re testingit()Defines a code exampleString we pass describes the specific behaviour
  • 3. describe() Methoddescribe “A User” {…}A Userdescribe User {…}Userdescribe User, “with no roles assigned” {…}User with no roles assigned
  • 5. context() methodcontext() is an alias for describe()Use describe() for things, context() for context
  • 6. it() methodArgument should state what is being tested
  • 7. Pending testsWe can mark tests to be implemented “later”
  • 8. Pending tests (cont.)Each method of marking a test as pending has its usefulness:Add pending examples as you think of stuff to testDisable failing examples without losing track that you need to fix those at some pointWrap failing examples when you want to be notified when changes to the system cause them to pass (bug is fixed, etc)
  • 9. before()/after() methodBefore/after methods helps you set and/or reset initial stateCreate a new stack, add one element to itTakes one argument:eachExecutes this block before each test group executes:allExecutes this block once for all tests before the first test is run
  • 11. before(:all)Method is run once and only once for a group of testsBe careful using this method, usually we want each test to have it’s own environment setupSharing state between examples can cause unexpected thingsGood examples:Opening a network connectionPre-seeding caches
  • 12. after(:each) methodCode is ran after each exampleRarely necessary because each example runs in its own scope, and consequently the instance variables in that scope are resetCan be useful to reset global state of things after your test completesafter(:each) is guaranteed to run after each example, even if failure or errors are raised
  • 14. after(:all) methodThis is even more rare than the after(:each)Examples:Close down browsersClose database connectionsClose socketsAny resource we want to release when we’re done, but not after every individual test
  • 15. around(:each) methodSupports APIs that require a blockVery rarely, if ever usedI have never used thisPut your functionality into before/after blocks if at all possibleSee http://relishapp.com/rspec/rspec-core/v/2-0/dir/hooks/around-hooks if you’re interested
  • 16. Helper MethodsDefined within an example groupAvailable to all examples in the group
  • 17. Shared Helper MethodsIf helper methods need to be used across example groups, put them in one or more modules and include modules in example groups we want to have access
  • 18. Shared ExamplesIf we expect instances of more than one class to behave in the same way, a shared example group describes the behavior once and includes it in multiple example groups
  • 20. RSpec::ExpectationsOne goal of BDD is getting the words rightExpectations vs. AssertionsWe are setting an expectation of what should happen rather than what will happenIn fact the word should is part of RSpecresult.should equal(5)message.should match(/on Sunday/)
  • 21. should, should_not and matchersresult.should equal(5)If result is equal to 5, it passesresult.should_not equal(5)If result is anything other than 5, it passesGeneral Pattern:result.should ________(value)_______ is a matcher
  • 22. RSpec built in Matchersinclude(item)prime_numbers.should_not include(8)respond_to(message)list.shouldrespond_to(:length)raise_error(type)lambda { Object.new.explode! }.should raise_error(NameError)
  • 23. 4 ways to be equala == bValue equality (Most common)a === bIs Object a the same Object as ba.eql?(b)Are a and b values equal and of same typea.equal?(b)Is Object a the same Object as b(General Rule: The longer the method name, the more restrictive the matcher is)
  • 24. Do not use != in expectationsactual.should != expectedaction.should_not == expectedCauses issues, explained in detail in the RSpec book
  • 25. Floating Point Calculations“expected 5.25 got 5.251” is frustrating in a failure messageRSpec offers a be_close matcher that accepts an expected value and an acceptable deltaresult.shouldbe_close(5.25, 0.005)Will pass as long as result is within .005 of 5.25
  • 26. Matching Textresponse.should match(/this expression/)Matches if response has text “this expression” somewhere in its contentsresponse.should =~ /this expression/Functionally equivalent to the previous one
  • 27. Expect{}Tests that a block of code causes some effectYou can also use .to(1) or .from(0).to(1)
  • 28. Predicate MatchersHow do we test array.empty?array.empty?.should == truearray.shouldbe_empty
  • 29. Predicate matchers (cont.)RSpec gives you other optionsbe_be_ated.shouldbe_a_kind_of(Player) => ted.kind_of?(Player)be_anted.shouldbe_an_instance_of(Player) =>ted.instance_of?(Player)RSpec also lets you write your own matchers
  • 30. Matchershave_ becomes has_request_params.shouldhave_key(:id) =>request_params.has_key?(:id).should == true
  • 31. specify{}Sometimes RSpec can guess your testsit “should have 32 pieces” do @board.should have(32).piecesendspecify { @board.should have(32).pieces }This is used rarely (very simple tests)
  • 32. subject {}Clean up your tests by specifying a subject
  • 33. RSpec MocksMocks allow you to fake functionality that isn’t being tested. See the book for more info.
  • 34. rspec commandrspec –helpList options available to running RSpecrspec spec/simple_math_spec.rbRun only one spec filerspec specRun all specs in spec/ directoryrspec spec --format documentationMakes RSpec more verbose with test output
  • 35. rspec commands (cont.)rspec spec –colorPassing is green, pending is yellow, fail is redStore common options in .rspec file--color--format documentationOptions stored in ./.rspec take precedence over ~/.rspec, options declared command line win
  • 36. Let’s get startedmkdir -p calculator/{lib,spec}cd calculatormate .

Editor's Notes

  • #29: Thebe_XXXX test works only if the item you called should on has a XXXX? method.
  • #33: If the should method doesn’t have an explicit receiver, it will delegate to the declared subject.Read your tests out loud to make sure they sound right. “Specify the subject should be eligible to vote” vs “it should be eligible to vote”.
  • #34: should_receive will error if :name is not calledstub will not error if :occupation is not called