SlideShare une entreprise Scribd logo
1  sur  23
Télécharger pour lire hors ligne
Bag o’ Tricks: Unit Testing

        Anton ’tony’ Bangratz
 https://abangratz.github.com/
           @tony_xpro
anton.bangratz@radarservices.com

            2012-01-18
Introduction
The Art of Testing
Not (only) Rails
One Method, One Purpose

Consider:
 class TitanClass
   .
   .
   .
   def doIt(*args)
     args[:external_sources].each do |source|
       args[:data_gatherers] do |gatherer|
         gatherer.doIt(source)
       end
     end
     processed_data = []
     current_gatherers.each do |gatherer|
       processed_data << process_data(gatherer)
     end
     reports = {}
     processed_data.each do |data|
       reports[data.id] = Report.new(data)
     end
     ReportPrinter.print_all(reports)
   end
 end
One Method, One Purpose

Test:
 require ’spec_helper’

 describe TitanClass do
   it "should do everything" do
     source = double(Source)
     gatherer = double(Gatherer)
     args = {external_sources: [source],
       data_gatherers: [gatherer]}
     processed = double("ProcessedData")
     subject.should_receive(process_data)
       .with(gatherer).and_return(processed)
     report = double(Report)
     Report.should_receive(:new).with(processed).
       and_return(report)
     ReportPrinter.should_receive(:print_all).with([report])
     subject.doIt(args)
   end
 end
One Method, One Purpose

Test:
 require ’spec_helper’

 describe TitanClass do
   it "should do everything" do
     source = double(Source)
     gatherer = double(Gatherer)
     args = {external_sources: [source],
       data_gatherers: [gatherer]}
     processed = double("ProcessedData")
     subject.should_receive(process_data)
       .with(gatherer).and_return(processed)
     # Yikes, a stub on the subject under test!
     report = double(Report)
     Report.should_receive(:new).with(processed).
       and_return(report)
     # Stubbing ".new" is rarely a good idea
     ReportPrinter.should_receive(:print_all).with([report])
     # Huh. We know that a ReportPrinter prints reports,
     # but that’s more than we actually should know ...
     subject.doIt(args)
   end
One Test, One Assertion
Example


describe SmartClass do
  it "invokes the data gatherer" do
    data_gatherer = double(DataGatherer)
    source = double(Source)
    data_gatherer.should_receive(gather).with(source))
    # Our only assertion!
    subject.data_gatherer = data_gatherer # DI for the win
    subject.gather_from_source(source)
  end end
...
class SmartClass

  attr_accessor :data_gatherer

  def gather_from_source(source)
    data_gatherer_gather(source)
  end
end
Mocking and Stubbing
Testing Modules
Example


class TestSmartModule
  include SmartModule
end
describe SmartModule do
  subject { TestSmartModule.new }
  it "does something" do
    subject.something.should ...
  end
end
Testing IO
Well, Rails
Anonymous Controllers
Example


describe SomeClass, type: ’controller’ do
  controller(ApplicationControllerOrSubClass) do
    def index
      ... # do something
    end
  end

  it "makes something happen" do
    ... # assert something happens
    get :index
  end
end
Testing Models?
Another Layer
TDD
Frameworks
MiniTest or RSpec?
That’s all, folks.
Thanks

•              ¨
    Stephan Kamper
•   Lisa Crispin
•   Elisabeth Hendricks
•   Michael Bolton
•   Avdi Grimm
•   Steve Klabnik
•   Jeremy Evans
•                 ¨
    Martin Gamsjager
•   Robert C. Martin (Uncle Bob)
•   Andreas Kopecky
•   Jurgen Strobel
     ¨
•   Andreas Tiefenthaler
•   Michael Kohl
•   Floor Drees
•   Friends and colleagues that inspired me

Contenu connexe

Tendances

Przywitaj się z reactive extensions
Przywitaj się z reactive extensionsPrzywitaj się z reactive extensions
Przywitaj się z reactive extensionsMarcin Juraszek
 
Data visualization by Kenneth Odoh
Data visualization by Kenneth OdohData visualization by Kenneth Odoh
Data visualization by Kenneth Odohpyconfi
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書くShoichi Matsuda
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationJoni
 
Metaprogramming in .NET
Metaprogramming in .NETMetaprogramming in .NET
Metaprogramming in .NETjasonbock
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiNexus FrontierTech
 
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...Mail.ru Group
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleGeoff Ballinger
 
Taming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a timeTaming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a timeSusanna Wong
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentSheeju Alex
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on AndroidGuilherme Branco
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805t k
 
GPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionGPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionVaclav Pech
 
Coherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherenceCoherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherencearagozin
 
Qtp certification questions and tutorial
Qtp certification questions and tutorialQtp certification questions and tutorial
Qtp certification questions and tutorialRamu Palanki
 
#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET Developers#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET DevelopersFrederik De Bruyne
 

Tendances (20)

Przywitaj się z reactive extensions
Przywitaj się z reactive extensionsPrzywitaj się z reactive extensions
Przywitaj się z reactive extensions
 
Data visualization by Kenneth Odoh
Data visualization by Kenneth OdohData visualization by Kenneth Odoh
Data visualization by Kenneth Odoh
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書く
 
Caching a page
Caching a pageCaching a page
Caching a page
 
Testing the unpredictable
Testing the unpredictableTesting the unpredictable
Testing the unpredictable
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Metaprogramming in .NET
Metaprogramming in .NETMetaprogramming in .NET
Metaprogramming in .NET
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
 
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Taming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a timeTaming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a time
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Gpars workshop
Gpars workshopGpars workshop
Gpars workshop
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on Android
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
GPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionGPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstraction
 
Coherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherenceCoherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherence
 
Qtp certification questions and tutorial
Qtp certification questions and tutorialQtp certification questions and tutorial
Qtp certification questions and tutorial
 
#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET Developers#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET Developers
 

Similaire à Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013

Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test communityKerry Buckley
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212Mahmoud Samir Fayed
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGvraopolisetti
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowRomain Dorgueil
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testingroisagiv
 
The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185Mahmoud Samir Fayed
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesDavid Rodenas
 
The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184Mahmoud Samir Fayed
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkitwlscaudill
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreXavier Coulon
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
 

Similaire à Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013 (20)

Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test community
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
ppopoff
ppopoffppopoff
ppopoff
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testing
 
The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD Techniques
 
The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Grails queries
Grails   queriesGrails   queries
Grails queries
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a Datastore
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 

Dernier

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 

Dernier (20)

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 

Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013

  • 1. Bag o’ Tricks: Unit Testing Anton ’tony’ Bangratz https://abangratz.github.com/ @tony_xpro anton.bangratz@radarservices.com 2012-01-18
  • 3. The Art of Testing
  • 5. One Method, One Purpose Consider: class TitanClass . . . def doIt(*args) args[:external_sources].each do |source| args[:data_gatherers] do |gatherer| gatherer.doIt(source) end end processed_data = [] current_gatherers.each do |gatherer| processed_data << process_data(gatherer) end reports = {} processed_data.each do |data| reports[data.id] = Report.new(data) end ReportPrinter.print_all(reports) end end
  • 6. One Method, One Purpose Test: require ’spec_helper’ describe TitanClass do it "should do everything" do source = double(Source) gatherer = double(Gatherer) args = {external_sources: [source], data_gatherers: [gatherer]} processed = double("ProcessedData") subject.should_receive(process_data) .with(gatherer).and_return(processed) report = double(Report) Report.should_receive(:new).with(processed). and_return(report) ReportPrinter.should_receive(:print_all).with([report]) subject.doIt(args) end end
  • 7. One Method, One Purpose Test: require ’spec_helper’ describe TitanClass do it "should do everything" do source = double(Source) gatherer = double(Gatherer) args = {external_sources: [source], data_gatherers: [gatherer]} processed = double("ProcessedData") subject.should_receive(process_data) .with(gatherer).and_return(processed) # Yikes, a stub on the subject under test! report = double(Report) Report.should_receive(:new).with(processed). and_return(report) # Stubbing ".new" is rarely a good idea ReportPrinter.should_receive(:print_all).with([report]) # Huh. We know that a ReportPrinter prints reports, # but that’s more than we actually should know ... subject.doIt(args) end
  • 8. One Test, One Assertion
  • 9. Example describe SmartClass do it "invokes the data gatherer" do data_gatherer = double(DataGatherer) source = double(Source) data_gatherer.should_receive(gather).with(source)) # Our only assertion! subject.data_gatherer = data_gatherer # DI for the win subject.gather_from_source(source) end end ... class SmartClass attr_accessor :data_gatherer def gather_from_source(source) data_gatherer_gather(source) end end
  • 12. Example class TestSmartModule include SmartModule end describe SmartModule do subject { TestSmartModule.new } it "does something" do subject.something.should ... end end
  • 16. Example describe SomeClass, type: ’controller’ do controller(ApplicationControllerOrSubClass) do def index ... # do something end end it "makes something happen" do ... # assert something happens get :index end end
  • 19. TDD
  • 23. Thanks • ¨ Stephan Kamper • Lisa Crispin • Elisabeth Hendricks • Michael Bolton • Avdi Grimm • Steve Klabnik • Jeremy Evans • ¨ Martin Gamsjager • Robert C. Martin (Uncle Bob) • Andreas Kopecky • Jurgen Strobel ¨ • Andreas Tiefenthaler • Michael Kohl • Floor Drees • Friends and colleagues that inspired me