SlideShare a Scribd company logo
1 of 38
Rspec 101 Jason Noble http://jasonnoble.org
Example Group describe() Defines example group of tests String we pass describes the item we’re testing it() Defines a code example String we pass describes the specific behaviour
describe() Method describe “A User” {…} A User describe User {…} User describe User, “with no roles assigned” {…} User with no roles assigned
Describe blocks can be nested
context() method context() is an alias for describe() Use describe() for things, context() for context
it() method Argument should state what is being tested
Pending tests We 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 test Disable failing examples without losing track that you need to fix those at some point Wrap failing examples when you want to be notified when changes to the system cause them to pass (bug is fixed, etc)
before()/after() method Before/after methods helps you set and/or reset initial state Create a new stack, add one element to it Takes one argument :each Executes this block before each test group executes :all Executes 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 tests Be careful using this method, usually we want each test to have it’s own environment setup Sharing state between examples can cause unexpected things Good examples: Opening a network connection Pre-seeding caches
after(:each) method Code is ran after each example Rarely necessary because each example runs in its own scope, and consequently the instance variables in that scope are reset Can be useful to reset global state of things after your test completes after(:each) is guaranteed to run after each example, even if failure or errors are raised
after(:each) example
after(:all) method This is even more rare than the after(:each) Examples: Close down browsers Close database connections Close sockets Any resource we want to release when we’re done, but not after every individual test
around(:each) method Supports APIs that require a block Very rarely, if ever used I have never used this Put your functionality into before/after blocks if at all possible See http://relishapp.com/rspec/rspec-core/v/2-0/dir/hooks/around-hooks if you’re interested
Helper Methods Defined within an example group Available to all examples in the group
Shared Helper Methods If 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 Examples If 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::Expectations One goal of BDD is getting the words right Expectations vs. Assertions We are setting an expectation of what should happen rather than what will happen In fact the word should is part of RSpec result.should equal(5) message.should match(/on Sunday/)
should, should_not and matchers result.should equal(5) If result is equal to 5, it passes result.should_not equal(5) If result is anything other than 5, it passes General Pattern:result.should   ________(value) _______ is a matcher
RSpec built in Matchers include(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 equal a == b Value equality (Most common) a === b Is Object a the same Object as b a.eql?(b) Are a and b values equal and of same type a.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 expectations actual.should != expected action.should_not == expected Causes issues, explained in detail in the RSpec book
Floating Point Calculations “expected 5.25 got 5.251” is frustrating in a failure message RSpec offers a be_close matcher that accepts an expected value and an acceptable delta result.shouldbe_close(5.25, 0.005) Will pass as long as result is within .005 of 5.25
Matching Text response.should match(/this expression/) Matches if response has text “this expression” somewhere in its contents response.should =~ /this expression/ Functionally equivalent to the previous one
Expect{} Tests that a block of code causes some effect You can also use .to(1) or .from(0).to(1)
Predicate Matchers How do we test array.empty? array.empty?.should == true array.shouldbe_empty
Predicate matchers (cont.) RSpec gives you other options be_ be_a ted.shouldbe_a_kind_of(Player)  => ted.kind_of?(Player) be_an ted.shouldbe_an_instance_of(Player) =>ted.instance_of?(Player) RSpec also lets you write your own matchers
Matchers have_ becomes has_ request_params.shouldhave_key(:id) =>request_params.has_key?(:id).should == true
specify{} Sometimes RSpec can guess your tests it “should have 32 pieces” do	@board.should have(32).piecesend specify { @board.should have(32).pieces } This is used rarely (very simple tests)
subject {} Clean up your tests by specifying a subject
RSpec Mocks Mocks allow you to fake functionality that isn’t being tested.  See the book for more info.
rspec command rspec –help List options available to running RSpec rspec spec/simple_math_spec.rb Run only one spec file rspec spec Run all specs in spec/ directory rspec spec --format documentation Makes RSpec more verbose with test output
rspec commands (cont.) rspec spec –color Passing is green, pending is yellow, fail is red Store common options in .rspec file --color --format documentation Options stored in ./.rspec take precedence over ~/.rspec, options declared command line win
Let’s get started mkdir -p calculator/{lib,spec} cd calculator mate .
spec/calculator_spec.rb lib/calculator.rb
spec/calculator_spec.rb

More Related Content

What's hot

How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
Rspec API Documentation
Rspec API DocumentationRspec API Documentation
Rspec API DocumentationSmartLogic
 
Perl Tidy Perl Critic
Perl Tidy Perl CriticPerl Tidy Perl Critic
Perl Tidy Perl Criticolegmmiller
 
Introduction to Python decorators
Introduction to Python decoratorsIntroduction to Python decorators
Introduction to Python decoratorsrikbyte
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4Yi-Huan Chan
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Samyak Bhalerao
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven DevelopmentKerry Buckley
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Katy Slemon
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesNaresha K
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripeIngo Schommer
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 

What's hot (20)

How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Rspec API Documentation
Rspec API DocumentationRspec API Documentation
Rspec API Documentation
 
Ruby on rails rspec
Ruby on rails rspecRuby on rails rspec
Ruby on rails rspec
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
Perl Tidy Perl Critic
Perl Tidy Perl CriticPerl Tidy Perl Critic
Perl Tidy Perl Critic
 
Introduction to Python decorators
Introduction to Python decoratorsIntroduction to Python decorators
Introduction to Python decorators
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
 
TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven Development
 
TDD with PhpSpec
TDD with PhpSpecTDD with PhpSpec
TDD with PhpSpec
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good Practices
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
jasmine
jasminejasmine
jasmine
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 

Viewers also liked

Testing with Rspec 3
Testing with Rspec 3Testing with Rspec 3
Testing with Rspec 3David Paluy
 
Monitoring web application behaviour with cucumber-nagios
Monitoring web application behaviour with cucumber-nagiosMonitoring web application behaviour with cucumber-nagios
Monitoring web application behaviour with cucumber-nagiosLindsay Holmwood
 
Automated testing with RSpec
Automated testing with RSpecAutomated testing with RSpec
Automated testing with RSpecNascenia IT
 
Serverspec and Sensu - Testing and Monitoring collide
Serverspec and Sensu - Testing and Monitoring collideServerspec and Sensu - Testing and Monitoring collide
Serverspec and Sensu - Testing and Monitoring collidem_richardson
 
Behavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and javaBehavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and javaNaveen Kumar Singh
 
Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with CucumberAsheesh Mehdiratta
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails TutorialWen-Tien Chang
 
Introduction to BDD with Cucumber for Java
Introduction to BDD with Cucumber for JavaIntroduction to BDD with Cucumber for Java
Introduction to BDD with Cucumber for JavaSeb Rose
 
Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with CucumberBrandon Keepers
 

Viewers also liked (12)

Testing with Rspec 3
Testing with Rspec 3Testing with Rspec 3
Testing with Rspec 3
 
MacRuby
MacRubyMacRuby
MacRuby
 
Basic RSpec 2
Basic RSpec 2Basic RSpec 2
Basic RSpec 2
 
Monitoring web application behaviour with cucumber-nagios
Monitoring web application behaviour with cucumber-nagiosMonitoring web application behaviour with cucumber-nagios
Monitoring web application behaviour with cucumber-nagios
 
Automated testing with RSpec
Automated testing with RSpecAutomated testing with RSpec
Automated testing with RSpec
 
Serverspec and Sensu - Testing and Monitoring collide
Serverspec and Sensu - Testing and Monitoring collideServerspec and Sensu - Testing and Monitoring collide
Serverspec and Sensu - Testing and Monitoring collide
 
Behavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and javaBehavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and java
 
Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
Introduction to BDD with Cucumber for Java
Introduction to BDD with Cucumber for JavaIntroduction to BDD with Cucumber for Java
Introduction to BDD with Cucumber for Java
 
Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
 
RSpec 2 Best practices
RSpec 2 Best practicesRSpec 2 Best practices
RSpec 2 Best practices
 

Similar to Rspec 101

Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5dplunkett
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
11 advance inheritance_concepts
11 advance inheritance_concepts11 advance inheritance_concepts
11 advance inheritance_conceptsArriz San Juan
 
The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185Mahmoud Samir Fayed
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)mussawir20
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnitAktuğ Urun
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulationİbrahim Kürce
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsimedo.de
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using SpockAnuj Aneja
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 

Similar to Rspec 101 (20)

Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
11 advance inheritance_concepts
11 advance inheritance_concepts11 advance inheritance_concepts
11 advance inheritance_concepts
 
The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185
 
Java mcq
Java mcqJava mcq
Java mcq
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
 
Unit testing
Unit testingUnit testing
Unit testing
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using Spock
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
11 ruby methods
11 ruby methods11 ruby methods
11 ruby methods
 

More from Jason Noble

Intro to TDD and BDD
Intro to TDD and BDDIntro to TDD and BDD
Intro to TDD and BDDJason Noble
 
Davinci git brown_bag
Davinci git brown_bagDavinci git brown_bag
Davinci git brown_bagJason Noble
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaJason Noble
 
Cart creation-101217222728-phpapp01
Cart creation-101217222728-phpapp01Cart creation-101217222728-phpapp01
Cart creation-101217222728-phpapp01Jason Noble
 
Validation unit testing
Validation unit testingValidation unit testing
Validation unit testingJason Noble
 
Creating the application
Creating the applicationCreating the application
Creating the applicationJason Noble
 
Atlanta Pm Git 101
Atlanta Pm Git 101Atlanta Pm Git 101
Atlanta Pm Git 101Jason Noble
 

More from Jason Noble (17)

Intro to TDD and BDD
Intro to TDD and BDDIntro to TDD and BDD
Intro to TDD and BDD
 
Davinci git brown_bag
Davinci git brown_bagDavinci git brown_bag
Davinci git brown_bag
 
Dash of ajax
Dash of ajaxDash of ajax
Dash of ajax
 
jQuery Intro
jQuery IntrojQuery Intro
jQuery Intro
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp Atlanta
 
Google apps
Google appsGoogle apps
Google apps
 
Smarter cart
Smarter cartSmarter cart
Smarter cart
 
Cart creation-101217222728-phpapp01
Cart creation-101217222728-phpapp01Cart creation-101217222728-phpapp01
Cart creation-101217222728-phpapp01
 
Catalog display
Catalog displayCatalog display
Catalog display
 
Validation unit testing
Validation unit testingValidation unit testing
Validation unit testing
 
Creating the application
Creating the applicationCreating the application
Creating the application
 
Capistrano
CapistranoCapistrano
Capistrano
 
Atlanta Pm Git 101
Atlanta Pm Git 101Atlanta Pm Git 101
Atlanta Pm Git 101
 
Regex Intro
Regex IntroRegex Intro
Regex Intro
 
Git101
Git101Git101
Git101
 
Git Atlrug
Git AtlrugGit Atlrug
Git Atlrug
 
Git102
Git102Git102
Git102
 

Recently uploaded

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Rspec 101

  • 1. Rspec 101 Jason Noble http://jasonnoble.org
  • 2. Example Group describe() Defines example group of tests String we pass describes the item we’re testing it() Defines a code example String we pass describes the specific behaviour
  • 3. describe() Method describe “A User” {…} A User describe User {…} User describe User, “with no roles assigned” {…} User with no roles assigned
  • 5. context() method context() is an alias for describe() Use describe() for things, context() for context
  • 6. it() method Argument should state what is being tested
  • 7. Pending tests We 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 test Disable failing examples without losing track that you need to fix those at some point Wrap failing examples when you want to be notified when changes to the system cause them to pass (bug is fixed, etc)
  • 9. before()/after() method Before/after methods helps you set and/or reset initial state Create a new stack, add one element to it Takes one argument :each Executes this block before each test group executes :all Executes 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 tests Be careful using this method, usually we want each test to have it’s own environment setup Sharing state between examples can cause unexpected things Good examples: Opening a network connection Pre-seeding caches
  • 12. after(:each) method Code is ran after each example Rarely necessary because each example runs in its own scope, and consequently the instance variables in that scope are reset Can be useful to reset global state of things after your test completes after(:each) is guaranteed to run after each example, even if failure or errors are raised
  • 14. after(:all) method This is even more rare than the after(:each) Examples: Close down browsers Close database connections Close sockets Any resource we want to release when we’re done, but not after every individual test
  • 15. around(:each) method Supports APIs that require a block Very rarely, if ever used I have never used this Put your functionality into before/after blocks if at all possible See http://relishapp.com/rspec/rspec-core/v/2-0/dir/hooks/around-hooks if you’re interested
  • 16. Helper Methods Defined within an example group Available to all examples in the group
  • 17. Shared Helper Methods If 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 Examples If 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::Expectations One goal of BDD is getting the words right Expectations vs. Assertions We are setting an expectation of what should happen rather than what will happen In fact the word should is part of RSpec result.should equal(5) message.should match(/on Sunday/)
  • 21. should, should_not and matchers result.should equal(5) If result is equal to 5, it passes result.should_not equal(5) If result is anything other than 5, it passes General Pattern:result.should ________(value) _______ is a matcher
  • 22. RSpec built in Matchers include(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 equal a == b Value equality (Most common) a === b Is Object a the same Object as b a.eql?(b) Are a and b values equal and of same type a.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 expectations actual.should != expected action.should_not == expected Causes issues, explained in detail in the RSpec book
  • 25. Floating Point Calculations “expected 5.25 got 5.251” is frustrating in a failure message RSpec offers a be_close matcher that accepts an expected value and an acceptable delta result.shouldbe_close(5.25, 0.005) Will pass as long as result is within .005 of 5.25
  • 26. Matching Text response.should match(/this expression/) Matches if response has text “this expression” somewhere in its contents response.should =~ /this expression/ Functionally equivalent to the previous one
  • 27. Expect{} Tests that a block of code causes some effect You can also use .to(1) or .from(0).to(1)
  • 28. Predicate Matchers How do we test array.empty? array.empty?.should == true array.shouldbe_empty
  • 29. Predicate matchers (cont.) RSpec gives you other options be_ be_a ted.shouldbe_a_kind_of(Player) => ted.kind_of?(Player) be_an ted.shouldbe_an_instance_of(Player) =>ted.instance_of?(Player) RSpec also lets you write your own matchers
  • 30. Matchers have_ becomes has_ request_params.shouldhave_key(:id) =>request_params.has_key?(:id).should == true
  • 31. specify{} Sometimes RSpec can guess your tests it “should have 32 pieces” do @board.should have(32).piecesend specify { @board.should have(32).pieces } This is used rarely (very simple tests)
  • 32. subject {} Clean up your tests by specifying a subject
  • 33. RSpec Mocks Mocks allow you to fake functionality that isn’t being tested. See the book for more info.
  • 34. rspec command rspec –help List options available to running RSpec rspec spec/simple_math_spec.rb Run only one spec file rspec spec Run all specs in spec/ directory rspec spec --format documentation Makes RSpec more verbose with test output
  • 35. rspec commands (cont.) rspec spec –color Passing is green, pending is yellow, fail is red Store common options in .rspec file --color --format documentation Options stored in ./.rspec take precedence over ~/.rspec, options declared command line win
  • 36. Let’s get started mkdir -p calculator/{lib,spec} cd calculator mate .

Editor's Notes

  1. Thebe_XXXX test works only if the item you called should on has a XXXX? method.
  2. 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”.
  3. should_receive will error if :name is not calledstub will not error if :occupation is not called