SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
Yi-Huan Chan
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
Yi-Huan Chan
 

Mais procurados (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
 

Destaque

Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
Brandon Keepers
 

Destaque (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
 

Semelhante a Rspec 101

Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
dplunkett
 
11 advance inheritance_concepts
11 advance inheritance_concepts11 advance inheritance_concepts
11 advance inheritance_concepts
Arriz San Juan
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 

Semelhante a 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
 

Mais de Jason Noble

Davinci git brown_bag
Davinci git brown_bagDavinci git brown_bag
Davinci git brown_bag
Jason Noble
 
Validation unit testing
Validation unit testingValidation unit testing
Validation unit testing
Jason Noble
 

Mais de 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
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

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...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

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 .

Notas do Editor

  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