SlideShare une entreprise Scribd logo
1  sur  46
RSpec The What, How and Why?
What?
What is Rspec? A BDD Framework for Ruby
What is Rspec? A BDD Framework for Ruby A testing framework that supports BDD
What is BDD /[T|B]DD/: Just Tests ... Right?
/[T|B]DD/: Just Tests ... Right?
100% Code Coverage is Good.Good Code + 100% Coverage is Better. Feel Free make whatever you want out of the above picture
Enter BDD Dan North(ThoughtWorks) Teaching TDD was hard TDD needed Direction
The Tools of BDD Change Of Focus Interaction-Based Testing A Ubiquitous Language
Change of Focus 	Tests have a tendency of loosing focus of what we’re meant to be building. Too low level. test_cases.each {|case| case.shouldadd_business_value} tests which describe domain specific functions => specs Keeps focus. Gives direction.
Interaction-Based Testing As opposed to state-based testing OOP design principles: Object exposes methods which are the only thing that touch its internal state. Any change in state requires a method call. SO: Just test that the call is made. Mock out all neighboring objects. A true UNIT test.
Is that a Bad thing?<wait for the onslaught> HOLD ON! Doesn’t that mean that my tests are tightly coupled with my implementation?
HOW?
How Do I use Rspec (with rails)?
How Do I use Rspec (with rails)? gem install rspecrspec-rails
How Do I use Rspec (with rails)? gem install rspecrspec-rails ./script/generate rspec
The Rspec Files
A Word about Factories A easy-to-maintain replacement for fixtures (Finally some code!) More about creating your own strategies at the end of this presentation
spec_helper.rb Loaded at the beginning of ever spec file Put methods that can be used by all specs here.
Examples The equivalent of a unit test in RSpec
The Syntax describe “Unit#something” do before(:each) do 			@unit= Unit.new(params) end it “should return something” do 		@unit.something.should == ‘something’ end end
The Syntax describe “Unit#something” do before(:each) do 			@unit= Unit.new(params) end it “should return something” do 		@unit.something.should == ‘something’ end end EXAMPLE
The Syntax describe “Unit#something” do before(:each) do 			@unit= Unit.new(params) end it “should return something” do 		@unit.something.should == ‘something’ end end
The Syntax context “Unit#something” do before(:each) do 			@unit= Unit.new(params) end specify “should return something” do 		@unit.something.should == ‘something’ end end
The Syntax describe “Unit#something” do before(:each) do 			@unit= Unit.new(params) end it “should return something” do 		@unit.something.should == ‘something’ end end
The Syntax describe “Unit#something” do before(:each) do 			@unit= Unit.new(params) end it “should return something” do 		@unit.something.should == ‘something’ end end
The Syntax describe “Unit#something” do before(:each) do 			@unit= Unit.new(params) end it “should return something” do 		@unit.something.should == ‘something’ end end
The Syntax describe “Unit#something” do before(:each) do 			@unit= Unit.new(params) end it “should return something” do 		@unit.something.should == ‘something’ end end
The mocking/stubbing framework object.stub!(:foo => ‘bar’, :one => 1) object.stub!(:foo).and_return(‘bar’) mock_object= mock/mock_model(Klass, espectations= {:foo => ‘bar’}) mock_object.foo #=> ‘bar’ Tool for Interaction Testing: mock_object.should_receive(:message).exactly(n).times.with(params).and_return(val) Each of the methods in that chain take many different options. Ref: Links Raises error if the message isn’t received & with the parameters specified & with the correct freq.
Mocks Aren’t Stubs Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'. Mocks are […] objects pre-programmed with expectations which form a specification of the calls they are expected to receive. -Martin Fowler
Functional Tests(Controller Examples) Isolate controllers from the models(mocks) Big difference from Rails Functional Testing:  Also isolate it from the views. Integration is possible with integrate_views
Controller specific Expectations Response Expectations should be_success should render_template should be_redirect should redirect_to response.[assigns|flash|sessions] Routing Expectations route_for(:controller => …, :action => …).should == /…/…/ params_from( :get,"/hello/world").should == {:controller=>"hello”  ,:action => "world"}
View Examples Again<Yawn> Isolation is key. # example article = mock_model(Article)  article.should_receive(:author).and_return("J”) article.should_receive(:text).and_return("this is the text of the article")  assigns[:article] = article  assigns[:articles] = [article] # flash and params are also available # template <% for article in @articles -%> <!-- etc -->
View Specific Expectations response.shouldhave_tag #examples response.shouldhave_tag('div#interesting_div‘, contents)  # Contents can be Regexp or String response.shouldhave_tag("input[type=?][checked=?]", 'checkbox', 'checked')  response.shouldhave_tag('ul') do with_tag('li', 'list item 1')  with_tag('li', 'list item 2')  with_tag('li', 'list item 3')  end
Exercise
My Spec
WHY?
The RSpec Philosophy Clarity over Cleverness Completely isolate the unit under test i.e. Mock Everything
Pros and Cons More descriptive code == more lines of code Not very DRY Tight coupling of test and implementation. Easily understandable tests True unit tests Interoperability with other testing frameworks
Interaction Testing is a Guideline Not a rule Depends on what you are testing. Remember: Usually leads to better OO Design not always better tests.
Good News Rspec doesn’t force IBT on you Write tests that work best for you.
If we’re doing SBT with Rspec.Why not stick to Test::Unit? OPTIONS RSpec is versatile. Can do everything that Test::Unit does and then some. Undoubtedly better for adding new functionality
Why RSpec? RSpec is not just about RSpec. It's about BDD. It's about encouraging conversation about testing and looking at it in different ways. It's about illuminating the design, specification, collaboration and documentation aspects of tests, and thinking of them as executable examples of behaviour. You can do this all without RSpec, but RSpec aims to help with innovations like:  strings as example names pending examples nested groups for flexible organization should[_not] + matchers (inspired by hamcrest - a java library) one matcher supports both positive and negative expectations improved failure messages  flexible/readable/customizable output formats  built-in mocking framework  plain text scenarios (now in Cucumber) - David Chelimsky(RSpec lead developer)
More Quotes The problem I have with TDD is that its mindset takes us in a different direction... a wrong direction. – Dave Astels(RSpec Creator)
Thank You! Questions.  Pleeeeease!!
Links http://blog.dannorth.net/introducing-bdd/ http://benpryor.com/blog/2007/01/16/state-based-vs-interaction-based-unit-testing/ http://rspec.info http://rspec.rubyforge.org/rspec/1.2.6/ Why Rspec? [http://www.ruby-forum.com/topic/184933] Full List of expectation definition options http://asciicasts.com/episodes/157-rspec-matchers-macros

Contenu connexe

Tendances

Introduction to testing in Rails
Introduction to testing in RailsIntroduction to testing in Rails
Introduction to testing in Railsbenlcollins
 
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
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit TestingPrince Norin
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
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
 
Karate - MoT Dallas 26-Oct-2017
Karate - MoT Dallas 26-Oct-2017Karate - MoT Dallas 26-Oct-2017
Karate - MoT Dallas 26-Oct-2017Peter Thomas
 
Perl Tidy Perl Critic
Perl Tidy Perl CriticPerl Tidy Perl Critic
Perl Tidy Perl Criticolegmmiller
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripeIngo Schommer
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplicationolegmmiller
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScriptpamselle
 
MidwestJS Zero to Testing
MidwestJS Zero to TestingMidwestJS Zero to Testing
MidwestJS Zero to Testingpamselle
 
2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with DreddRyan M Harrison
 

Tendances (20)

Factory Girl
Factory GirlFactory Girl
Factory Girl
 
Introduction to testing in Rails
Introduction to testing in RailsIntroduction to testing in Rails
Introduction to testing in Rails
 
TDD with phpspec2
TDD with phpspec2TDD with phpspec2
TDD with phpspec2
 
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
 
Ruby on rails rspec
Ruby on rails rspecRuby on rails rspec
Ruby on rails rspec
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
 
TDD with PhpSpec
TDD with PhpSpecTDD with PhpSpec
TDD with PhpSpec
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
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...
 
Karate - MoT Dallas 26-Oct-2017
Karate - MoT Dallas 26-Oct-2017Karate - MoT Dallas 26-Oct-2017
Karate - MoT Dallas 26-Oct-2017
 
Perl Tidy Perl Critic
Perl Tidy Perl CriticPerl Tidy Perl Critic
Perl Tidy Perl Critic
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Angular Unit Test
Angular Unit TestAngular Unit Test
Angular Unit Test
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScript
 
MidwestJS Zero to Testing
MidwestJS Zero to TestingMidwestJS Zero to Testing
MidwestJS Zero to Testing
 
2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd
 

En vedette

Testing with Rspec 3
Testing with Rspec 3Testing with Rspec 3
Testing with Rspec 3David Paluy
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Storiesrahoulb
 
Introduction to ATDD with Cucumber and RSpec
Introduction to ATDD with Cucumber and RSpecIntroduction to ATDD with Cucumber and RSpec
Introduction to ATDD with Cucumber and RSpecKenta Murata
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails TutorialWen-Tien Chang
 
DevDay 2016: Dave Farley - Acceptance testing for continuous delivery
DevDay 2016: Dave Farley - Acceptance testing for continuous deliveryDevDay 2016: Dave Farley - Acceptance testing for continuous delivery
DevDay 2016: Dave Farley - Acceptance testing for continuous deliveryDevDay Dresden
 
software testing
 software testing software testing
software testingSara shall
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Brian Sam-Bodden
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Software Testing Life Cycle
Software Testing Life CycleSoftware Testing Life Cycle
Software Testing Life CycleUdayakumar Sree
 
An Overview of User Acceptance Testing (UAT)
An Overview of User Acceptance Testing (UAT)An Overview of User Acceptance Testing (UAT)
An Overview of User Acceptance Testing (UAT)Usersnap
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesomeAndrew Hull
 
Software Testing Basics
Software Testing BasicsSoftware Testing Basics
Software Testing BasicsBelal Raslan
 
Introduction to Agile software testing
Introduction to Agile software testingIntroduction to Agile software testing
Introduction to Agile software testingKMS Technology
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing FundamentalsChankey Pathak
 
Software testing basic concepts
Software testing basic conceptsSoftware testing basic concepts
Software testing basic conceptsHưng Hoàng
 

En vedette (19)

Basic RSpec 2
Basic RSpec 2Basic RSpec 2
Basic RSpec 2
 
Testing with Rspec 3
Testing with Rspec 3Testing with Rspec 3
Testing with Rspec 3
 
MacRuby
MacRubyMacRuby
MacRuby
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Stories
 
Introduction to ATDD with Cucumber and RSpec
Introduction to ATDD with Cucumber and RSpecIntroduction to ATDD with Cucumber and RSpec
Introduction to ATDD with Cucumber and RSpec
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
DevDay 2016: Dave Farley - Acceptance testing for continuous delivery
DevDay 2016: Dave Farley - Acceptance testing for continuous deliveryDevDay 2016: Dave Farley - Acceptance testing for continuous delivery
DevDay 2016: Dave Farley - Acceptance testing for continuous delivery
 
software testing
 software testing software testing
software testing
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Software Testing Life Cycle
Software Testing Life CycleSoftware Testing Life Cycle
Software Testing Life Cycle
 
An Overview of User Acceptance Testing (UAT)
An Overview of User Acceptance Testing (UAT)An Overview of User Acceptance Testing (UAT)
An Overview of User Acceptance Testing (UAT)
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
Software Testing Basics
Software Testing BasicsSoftware Testing Basics
Software Testing Basics
 
Introduction to Agile software testing
Introduction to Agile software testingIntroduction to Agile software testing
Introduction to Agile software testing
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing Fundamentals
 
Software testing basic concepts
Software testing basic conceptsSoftware testing basic concepts
Software testing basic concepts
 
Software testing ppt
Software testing pptSoftware testing ppt
Software testing ppt
 

Similaire à RSpec: What, How and Why

BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit TestingWen-Tien Chang
 
Tdd is Dead, Long Live TDD
Tdd is Dead, Long Live TDDTdd is Dead, Long Live TDD
Tdd is Dead, Long Live TDDJonathan Acker
 
Introduction to unit testing
Introduction to unit testingIntroduction to unit testing
Introduction to unit testingArtem Shoobovych
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingMike Clement
 
Tips to make your rspec specs awesome
Tips to make your rspec specs awesomeTips to make your rspec specs awesome
Tips to make your rspec specs awesomeSwati Jadhav
 
Unit Test and TDD
Unit Test and TDDUnit Test and TDD
Unit Test and TDDViet Tran
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionDionatan default
 
TDD - A Reminder of the Principles
TDD - A Reminder of the PrinciplesTDD - A Reminder of the Principles
TDD - A Reminder of the PrinciplesMatthias Noback
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversBrian Gesiak
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 
[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
 

Similaire à RSpec: What, How and Why (20)

BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
Rspec
RspecRspec
Rspec
 
Refactoring
RefactoringRefactoring
Refactoring
 
Tdd is Dead, Long Live TDD
Tdd is Dead, Long Live TDDTdd is Dead, Long Live TDD
Tdd is Dead, Long Live TDD
 
Rtt preso
Rtt presoRtt preso
Rtt preso
 
Introduction to unit testing
Introduction to unit testingIntroduction to unit testing
Introduction to unit testing
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit Testing
 
Tips to make your rspec specs awesome
Tips to make your rspec specs awesomeTips to make your rspec specs awesome
Tips to make your rspec specs awesome
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Unit Test and TDD
Unit Test and TDDUnit Test and TDD
Unit Test and TDD
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
TDD - A Reminder of the Principles
TDD - A Reminder of the PrinciplesTDD - A Reminder of the Principles
TDD - A Reminder of the Principles
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
RSpec
RSpecRSpec
RSpec
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
[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
 

Dernier

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
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 WorkerThousandEyes
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Dernier (20)

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
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
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

RSpec: What, How and Why

  • 1. RSpec The What, How and Why?
  • 3. What is Rspec? A BDD Framework for Ruby
  • 4. What is Rspec? A BDD Framework for Ruby A testing framework that supports BDD
  • 5. What is BDD /[T|B]DD/: Just Tests ... Right?
  • 7. 100% Code Coverage is Good.Good Code + 100% Coverage is Better. Feel Free make whatever you want out of the above picture
  • 8. Enter BDD Dan North(ThoughtWorks) Teaching TDD was hard TDD needed Direction
  • 9. The Tools of BDD Change Of Focus Interaction-Based Testing A Ubiquitous Language
  • 10. Change of Focus Tests have a tendency of loosing focus of what we’re meant to be building. Too low level. test_cases.each {|case| case.shouldadd_business_value} tests which describe domain specific functions => specs Keeps focus. Gives direction.
  • 11. Interaction-Based Testing As opposed to state-based testing OOP design principles: Object exposes methods which are the only thing that touch its internal state. Any change in state requires a method call. SO: Just test that the call is made. Mock out all neighboring objects. A true UNIT test.
  • 12. Is that a Bad thing?<wait for the onslaught> HOLD ON! Doesn’t that mean that my tests are tightly coupled with my implementation?
  • 13. HOW?
  • 14. How Do I use Rspec (with rails)?
  • 15. How Do I use Rspec (with rails)? gem install rspecrspec-rails
  • 16. How Do I use Rspec (with rails)? gem install rspecrspec-rails ./script/generate rspec
  • 18. A Word about Factories A easy-to-maintain replacement for fixtures (Finally some code!) More about creating your own strategies at the end of this presentation
  • 19. spec_helper.rb Loaded at the beginning of ever spec file Put methods that can be used by all specs here.
  • 20. Examples The equivalent of a unit test in RSpec
  • 21. The Syntax describe “Unit#something” do before(:each) do @unit= Unit.new(params) end it “should return something” do @unit.something.should == ‘something’ end end
  • 22. The Syntax describe “Unit#something” do before(:each) do @unit= Unit.new(params) end it “should return something” do @unit.something.should == ‘something’ end end EXAMPLE
  • 23. The Syntax describe “Unit#something” do before(:each) do @unit= Unit.new(params) end it “should return something” do @unit.something.should == ‘something’ end end
  • 24. The Syntax context “Unit#something” do before(:each) do @unit= Unit.new(params) end specify “should return something” do @unit.something.should == ‘something’ end end
  • 25. The Syntax describe “Unit#something” do before(:each) do @unit= Unit.new(params) end it “should return something” do @unit.something.should == ‘something’ end end
  • 26. The Syntax describe “Unit#something” do before(:each) do @unit= Unit.new(params) end it “should return something” do @unit.something.should == ‘something’ end end
  • 27. The Syntax describe “Unit#something” do before(:each) do @unit= Unit.new(params) end it “should return something” do @unit.something.should == ‘something’ end end
  • 28. The Syntax describe “Unit#something” do before(:each) do @unit= Unit.new(params) end it “should return something” do @unit.something.should == ‘something’ end end
  • 29. The mocking/stubbing framework object.stub!(:foo => ‘bar’, :one => 1) object.stub!(:foo).and_return(‘bar’) mock_object= mock/mock_model(Klass, espectations= {:foo => ‘bar’}) mock_object.foo #=> ‘bar’ Tool for Interaction Testing: mock_object.should_receive(:message).exactly(n).times.with(params).and_return(val) Each of the methods in that chain take many different options. Ref: Links Raises error if the message isn’t received & with the parameters specified & with the correct freq.
  • 30. Mocks Aren’t Stubs Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'. Mocks are […] objects pre-programmed with expectations which form a specification of the calls they are expected to receive. -Martin Fowler
  • 31. Functional Tests(Controller Examples) Isolate controllers from the models(mocks) Big difference from Rails Functional Testing: Also isolate it from the views. Integration is possible with integrate_views
  • 32. Controller specific Expectations Response Expectations should be_success should render_template should be_redirect should redirect_to response.[assigns|flash|sessions] Routing Expectations route_for(:controller => …, :action => …).should == /…/…/ params_from( :get,"/hello/world").should == {:controller=>"hello” ,:action => "world"}
  • 33. View Examples Again<Yawn> Isolation is key. # example article = mock_model(Article) article.should_receive(:author).and_return("J”) article.should_receive(:text).and_return("this is the text of the article") assigns[:article] = article assigns[:articles] = [article] # flash and params are also available # template <% for article in @articles -%> <!-- etc -->
  • 34. View Specific Expectations response.shouldhave_tag #examples response.shouldhave_tag('div#interesting_div‘, contents) # Contents can be Regexp or String response.shouldhave_tag("input[type=?][checked=?]", 'checkbox', 'checked') response.shouldhave_tag('ul') do with_tag('li', 'list item 1') with_tag('li', 'list item 2') with_tag('li', 'list item 3') end
  • 37. WHY?
  • 38. The RSpec Philosophy Clarity over Cleverness Completely isolate the unit under test i.e. Mock Everything
  • 39. Pros and Cons More descriptive code == more lines of code Not very DRY Tight coupling of test and implementation. Easily understandable tests True unit tests Interoperability with other testing frameworks
  • 40. Interaction Testing is a Guideline Not a rule Depends on what you are testing. Remember: Usually leads to better OO Design not always better tests.
  • 41. Good News Rspec doesn’t force IBT on you Write tests that work best for you.
  • 42. If we’re doing SBT with Rspec.Why not stick to Test::Unit? OPTIONS RSpec is versatile. Can do everything that Test::Unit does and then some. Undoubtedly better for adding new functionality
  • 43. Why RSpec? RSpec is not just about RSpec. It's about BDD. It's about encouraging conversation about testing and looking at it in different ways. It's about illuminating the design, specification, collaboration and documentation aspects of tests, and thinking of them as executable examples of behaviour. You can do this all without RSpec, but RSpec aims to help with innovations like: strings as example names pending examples nested groups for flexible organization should[_not] + matchers (inspired by hamcrest - a java library) one matcher supports both positive and negative expectations improved failure messages flexible/readable/customizable output formats built-in mocking framework plain text scenarios (now in Cucumber) - David Chelimsky(RSpec lead developer)
  • 44. More Quotes The problem I have with TDD is that its mindset takes us in a different direction... a wrong direction. – Dave Astels(RSpec Creator)
  • 45. Thank You! Questions. Pleeeeease!!
  • 46. Links http://blog.dannorth.net/introducing-bdd/ http://benpryor.com/blog/2007/01/16/state-based-vs-interaction-based-unit-testing/ http://rspec.info http://rspec.rubyforge.org/rspec/1.2.6/ Why Rspec? [http://www.ruby-forum.com/topic/184933] Full List of expectation definition options http://asciicasts.com/episodes/157-rspec-matchers-macros

Notes de l'éditeur

  1. Introduced by Dan North in 2006Found that training people in TDD was hard since the process lacked direction.Mixed DDD(Domain Driven Design) + TDDStart with the requirements. Work inwards.The Tools:A change in language (tests -&gt; specs)Interaction-Based TestingDescriptive Tests
  2. The ProcessAs opposed to state-based testing(Test::Unit)Mock all immediate neighbors of a unit.Define Expectations of the mock objectsRun the unit &amp; Check if expectations are metObservationsTests get too intimate with implementationGood/Bad thing?Test behavior not state.Faster if done_right?A true Unit Test – Complete isolation of the unitAssumes that the interface is constant and the state is mutable.
  3. 1246 context &quot;when not available in cache&quot; do 1247 before do 1248 @slideshow= Factory(:slideshow, :user_id =&gt; @user.id) 1249 @tag_det= Factory(:tag_det, :slideshow =&gt; @slideshow) 1250 end 1251 it &quot;should return it from db&quot; do 1252 @user.tags.should ==[@tag_det] 1253 end 1254 1255 it &quot;should add the data to cache&quot; do 1256 Cache.should_receive(:put).with(&quot;TagDet:#{@user.id}&quot;, [@tag_det], anything) 1257 @user.tags1258 end 1259 end 1260 end