SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Testing HTTP calls
           Kerry Buckley
 IPRUG lightning talk, 5 March 2013
Why?
Your tests


 Your app


Webby stuff
Webmock
Test::Unit          Minitest     RSpec        Cucumber


                          Your app


                                              EM-HTTP-
Net::HTTP       HTTPclient       Patron
                                               request

             Curb         Typhoeus        Excon


                          Webmock
Setup
group :test do
  gem "webmock"
end

require 'webmock/rspec'

require 'webmock/minitest'

require 'webmock/test_unit'

require 'webmock/cucumber'
Basic stub

 stub_request :any,
 "www.example.com"

Net::HTTP.get "www.example.com", "/"

  # => 200 OK, body = ""
Filtering requests
 stub_request(:post, "www.example.com").
 with(body: "abc",
      headers: {'Content-Length' => 3})


stub_http_request(:post, "www.example.com").
  with(body: {data: {a: "1", b: "five"}})


stub_request(:post, "www.example.com").
  with {|request| some_checks(request) }
Response

stub_request(:any, "www.example.com").
  to_return(body: "abc",
            status: 200,
            headers: {'Content-Length' => 3} )

stub_request(:any, 'www.example.net').
  to_return {|request| {body: request.body} }
Raising exceptions
stub_request(:any, 'www.example.net').
  to_raise("some error")


stub_request(:any, 'www.example.net').
  to_raise(Errno::ECONNRESET.new("some error"))


stub_request(:any, 'www.example.net').
  to_raise(Errno::ETIMEDOUT)


stub_request(:any, 'www.example.net').to_timeout
Stubbing with Rack
class MyRackApp
  def self.call(env)
    [200, {}, ["Hello"]]
  end
end

stub_request(:get, "www.example.com").
  to_rack(MyRackApp)
Allow real requests
WebMock.allow_net_connect!

WebMock.disable_net_connect!(
  allow_localhost: true)

WebMock.disable_net_connect!(
  allow: "www.example.org:8080")
Expectations
require 'webmock/rspec'

WebMock.should_not have_requested(:get,
  "www.something.com")

WebMock.should have_requested(:get,
  "www.example.com").
  with(body: "abc",
       headers: {'Content-Length' => 3}).twice

WebMock.should have_requested(:get,
  "www.example.com").
  with(query: {"a" => ["b", "c"]})
Replaying curl
`curl -is www.example.com > /tmp/example.txt`
raw_response_file = File.new("/tmp/example.txt")


stub_request(:get, "www.example.com").
  to_return(raw_response_file)


stub_request(:get, "www.example.com").
  to_return(raw_response_file.read)
VCR
          Your tests

              Your app




Webby stuff
Setup
group :test do
  gem "vcr"
end

VCR.configure do |c|
  c.cassette_library_dir = "vcr_cassettes"
  c.hook_into :webmock
end

VCR.use_cassette("example-dot-com-index") do
  Net::HTTP.get "www.example.com", "/"
end
Library support
Test::Unit   Minitest         RSpec     Cucumber


                        VCR


Webmock      Fakeweb          Faraday    Excon


                   Typhoeus
RSpec
  RSpec.configure do |c|
  c.extend VCR::RSpec::Macros
end

describe "something" do
  use_vcr_cassette

  it "does something" do
    ...
  end
end
Cucumber
  VCR.cucumber_tags do |t|
  t.tag '@example-dot-com-index'
  t.tag '@example-dot-com-another-request'
end

Feature: VCR stuff

  @example-dot-com-index
  Scenario: Do something
    Given foo
    When bar
    Then baz
Cassettes
---
http_interactions:
- request:
    method: get
    uri: http://example.com/
    body: ''
    headers: {}
  response:
    status:
      code: 200
      message: OK
    headers:
      Content-Type:
      - text/html;charset=utf-8
      Content-Length:
      - '26'
    body: This is the response body
    http_version: '1.1'
  recorded_at: Tue, 01 Nov 2011 04:58:44 GMT
recorded_with: VCR 2.0.0
Request matching
VCR.configure do |c|
  c.default_cassette_options = {
    match_requests_on: [:method, :uri]}
end

Also available:

• :host
• :path
• :query
• :body
• :headers
Ignoring requests
 VCR.configure do |c|
 c.ignore_request do |request|
   URI(request.uri).port == 7777
 end

  c.ignore_hosts "foo.com", "bar.com"

  c.ignore_localhost = true
end
Summary
Use Webmock (or Fakeweb)
• For fine-grained control
• If remote server isn’t available
Use VCR
• When record/replay is enough
• For an easy life

Más contenido relacionado

La actualidad más candente

GPerf Using Jesque
GPerf Using JesqueGPerf Using Jesque
GPerf Using Jesquectoestreich
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slidesharetomcopeland
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go ConcurrencyCloudflare
 
Beyond Page Level Metrics
Beyond Page Level MetricsBeyond Page Level Metrics
Beyond Page Level MetricsPhilip Tellis
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardHow I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardSV Ruby on Rails Meetup
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHPKing Foo
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.jsPrabin Silwal
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisFastly
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent EventTencent
 
Puppet Performance Profiling
Puppet Performance ProfilingPuppet Performance Profiling
Puppet Performance Profilingripienaar
 
HTTPBuilder NG: Back From The Dead
HTTPBuilder NG: Back From The DeadHTTPBuilder NG: Back From The Dead
HTTPBuilder NG: Back From The Deadnoamt
 
Autoscaling with hashi_corp_nomad
Autoscaling with hashi_corp_nomadAutoscaling with hashi_corp_nomad
Autoscaling with hashi_corp_nomadBram Vogelaar
 
Testing your infrastructure with litmus
Testing your infrastructure with litmusTesting your infrastructure with litmus
Testing your infrastructure with litmusBram Vogelaar
 
Observability with Consul Connect
Observability with Consul ConnectObservability with Consul Connect
Observability with Consul ConnectBram Vogelaar
 
Http capturing
Http capturingHttp capturing
Http capturingEric Ahn
 
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...Willian Molinari
 
HTTP caching with Varnish
HTTP caching with VarnishHTTP caching with Varnish
HTTP caching with VarnishDavid de Boer
 
Boxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsBoxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsPuppet
 

La actualidad más candente (20)

GPerf Using Jesque
GPerf Using JesqueGPerf Using Jesque
GPerf Using Jesque
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshare
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Beyond Page Level Metrics
Beyond Page Level MetricsBeyond Page Level Metrics
Beyond Page Level Metrics
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardHow I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
 
Puppet Performance Profiling
Puppet Performance ProfilingPuppet Performance Profiling
Puppet Performance Profiling
 
HTTPBuilder NG: Back From The Dead
HTTPBuilder NG: Back From The DeadHTTPBuilder NG: Back From The Dead
HTTPBuilder NG: Back From The Dead
 
Autoscaling with hashi_corp_nomad
Autoscaling with hashi_corp_nomadAutoscaling with hashi_corp_nomad
Autoscaling with hashi_corp_nomad
 
Testing your infrastructure with litmus
Testing your infrastructure with litmusTesting your infrastructure with litmus
Testing your infrastructure with litmus
 
Observability with Consul Connect
Observability with Consul ConnectObservability with Consul Connect
Observability with Consul Connect
 
Http capturing
Http capturingHttp capturing
Http capturing
 
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
 
HTTP caching with Varnish
HTTP caching with VarnishHTTP caching with Varnish
HTTP caching with Varnish
 
Boxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsBoxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of Laptops
 

Similar a Testing http calls with Webmock and VCR

Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossugclkao
 
VUG5: Varnish at Opera Software
VUG5: Varnish at Opera SoftwareVUG5: Varnish at Opera Software
VUG5: Varnish at Opera SoftwareCosimo Streppone
 
Assurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring frameworkAssurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring frameworkGosuke Miyashita
 
How we use and deploy Varnish at Opera
How we use and deploy Varnish at OperaHow we use and deploy Varnish at Opera
How we use and deploy Varnish at OperaCosimo Streppone
 
Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests librarySusan Tan
 
REST meets Semantic Web
REST meets Semantic WebREST meets Semantic Web
REST meets Semantic WebSteve Speicher
 
Fargate 를 이용한 ECS with VPC 1부
Fargate 를 이용한 ECS with VPC 1부Fargate 를 이용한 ECS with VPC 1부
Fargate 를 이용한 ECS with VPC 1부Hyun-Mook Choi
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHPDavid de Boer
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberKMS Technology
 
Full Stack Load Testing
Full Stack Load Testing Full Stack Load Testing
Full Stack Load Testing Terral R Jordan
 
Comet from JavaOne 2008
Comet from JavaOne 2008Comet from JavaOne 2008
Comet from JavaOne 2008Joe Walker
 
How to ensure Presto scalability 
in multi use case
How to ensure Presto scalability 
in multi use case How to ensure Presto scalability 
in multi use case
How to ensure Presto scalability 
in multi use case Kai Sasaki
 
Istio Playground
Istio PlaygroundIstio Playground
Istio PlaygroundQAware GmbH
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesPavol Pitoňák
 
Altitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the EdgeAltitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the EdgeFastly
 

Similar a Testing http calls with Webmock and VCR (20)

Palestra VCR
Palestra VCRPalestra VCR
Palestra VCR
 
Nginx
NginxNginx
Nginx
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossug
 
VUG5: Varnish at Opera Software
VUG5: Varnish at Opera SoftwareVUG5: Varnish at Opera Software
VUG5: Varnish at Opera Software
 
Otimizando seu projeto Rails
Otimizando seu projeto RailsOtimizando seu projeto Rails
Otimizando seu projeto Rails
 
Assurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring frameworkAssurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring framework
 
How we use and deploy Varnish at Opera
How we use and deploy Varnish at OperaHow we use and deploy Varnish at Opera
How we use and deploy Varnish at Opera
 
Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests library
 
SmokeTests
SmokeTestsSmokeTests
SmokeTests
 
REST meets Semantic Web
REST meets Semantic WebREST meets Semantic Web
REST meets Semantic Web
 
Fargate 를 이용한 ECS with VPC 1부
Fargate 를 이용한 ECS with VPC 1부Fargate 를 이용한 ECS with VPC 1부
Fargate 를 이용한 ECS with VPC 1부
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using Cucumber
 
Full Stack Load Testing
Full Stack Load Testing Full Stack Load Testing
Full Stack Load Testing
 
Comet from JavaOne 2008
Comet from JavaOne 2008Comet from JavaOne 2008
Comet from JavaOne 2008
 
How to ensure Presto scalability 
in multi use case
How to ensure Presto scalability 
in multi use case How to ensure Presto scalability 
in multi use case
How to ensure Presto scalability 
in multi use case
 
Rack
RackRack
Rack
 
Istio Playground
Istio PlaygroundIstio Playground
Istio Playground
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile Devices
 
Altitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the EdgeAltitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the Edge
 

Más de Kerry Buckley

Ruby nooks & crannies
Ruby nooks & cranniesRuby nooks & crannies
Ruby nooks & cranniesKerry Buckley
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworksKerry Buckley
 
Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test communityKerry Buckley
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)Kerry Buckley
 
Adastral Park code retreat introduction
Adastral Park code retreat introductionAdastral Park code retreat introduction
Adastral Park code retreat introductionKerry Buckley
 
MongoMapper lightning talk
MongoMapper lightning talkMongoMapper lightning talk
MongoMapper lightning talkKerry Buckley
 
The secret life of bees
The secret life of beesThe secret life of bees
The secret life of beesKerry Buckley
 
Background processing
Background processingBackground processing
Background processingKerry Buckley
 
Katas, Contests and Coding Dojos
Katas, Contests and Coding DojosKatas, Contests and Coding Dojos
Katas, Contests and Coding DojosKerry Buckley
 
Kanban and Iterationless Working
Kanban and Iterationless WorkingKanban and Iterationless Working
Kanban and Iterationless WorkingKerry Buckley
 
Software Development Trends
Software Development TrendsSoftware Development Trends
Software Development TrendsKerry Buckley
 

Más de Kerry Buckley (20)

Jasmine
JasmineJasmine
Jasmine
 
BDD with cucumber
BDD with cucumberBDD with cucumber
BDD with cucumber
 
Ruby nooks & crannies
Ruby nooks & cranniesRuby nooks & crannies
Ruby nooks & crannies
 
TDD refresher
TDD refresherTDD refresher
TDD refresher
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworks
 
Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test community
 
7li7w devcon5
7li7w devcon57li7w devcon5
7li7w devcon5
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
 
Functional ruby
Functional rubyFunctional ruby
Functional ruby
 
Adastral Park code retreat introduction
Adastral Park code retreat introductionAdastral Park code retreat introduction
Adastral Park code retreat introduction
 
MongoMapper lightning talk
MongoMapper lightning talkMongoMapper lightning talk
MongoMapper lightning talk
 
Ruby
RubyRuby
Ruby
 
Cloud
CloudCloud
Cloud
 
The secret life of bees
The secret life of beesThe secret life of bees
The secret life of bees
 
Background processing
Background processingBackground processing
Background processing
 
Katas, Contests and Coding Dojos
Katas, Contests and Coding DojosKatas, Contests and Coding Dojos
Katas, Contests and Coding Dojos
 
Rack
RackRack
Rack
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Kanban and Iterationless Working
Kanban and Iterationless WorkingKanban and Iterationless Working
Kanban and Iterationless Working
 
Software Development Trends
Software Development TrendsSoftware Development Trends
Software Development Trends
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 

Testing http calls with Webmock and VCR

  • 1. Testing HTTP calls Kerry Buckley IPRUG lightning talk, 5 March 2013
  • 2. Why? Your tests Your app Webby stuff
  • 3. Webmock Test::Unit Minitest RSpec Cucumber Your app EM-HTTP- Net::HTTP HTTPclient Patron request Curb Typhoeus Excon Webmock
  • 4. Setup group :test do gem "webmock" end require 'webmock/rspec' require 'webmock/minitest' require 'webmock/test_unit' require 'webmock/cucumber'
  • 5. Basic stub stub_request :any, "www.example.com" Net::HTTP.get "www.example.com", "/" # => 200 OK, body = ""
  • 6. Filtering requests stub_request(:post, "www.example.com"). with(body: "abc", headers: {'Content-Length' => 3}) stub_http_request(:post, "www.example.com"). with(body: {data: {a: "1", b: "five"}}) stub_request(:post, "www.example.com"). with {|request| some_checks(request) }
  • 7. Response stub_request(:any, "www.example.com"). to_return(body: "abc", status: 200, headers: {'Content-Length' => 3} ) stub_request(:any, 'www.example.net'). to_return {|request| {body: request.body} }
  • 8. Raising exceptions stub_request(:any, 'www.example.net'). to_raise("some error") stub_request(:any, 'www.example.net'). to_raise(Errno::ECONNRESET.new("some error")) stub_request(:any, 'www.example.net'). to_raise(Errno::ETIMEDOUT) stub_request(:any, 'www.example.net').to_timeout
  • 9. Stubbing with Rack class MyRackApp def self.call(env) [200, {}, ["Hello"]] end end stub_request(:get, "www.example.com"). to_rack(MyRackApp)
  • 10. Allow real requests WebMock.allow_net_connect! WebMock.disable_net_connect!( allow_localhost: true) WebMock.disable_net_connect!( allow: "www.example.org:8080")
  • 11. Expectations require 'webmock/rspec' WebMock.should_not have_requested(:get, "www.something.com") WebMock.should have_requested(:get, "www.example.com"). with(body: "abc", headers: {'Content-Length' => 3}).twice WebMock.should have_requested(:get, "www.example.com"). with(query: {"a" => ["b", "c"]})
  • 12. Replaying curl `curl -is www.example.com > /tmp/example.txt` raw_response_file = File.new("/tmp/example.txt") stub_request(:get, "www.example.com"). to_return(raw_response_file) stub_request(:get, "www.example.com"). to_return(raw_response_file.read)
  • 13. VCR Your tests Your app Webby stuff
  • 14. Setup group :test do gem "vcr" end VCR.configure do |c| c.cassette_library_dir = "vcr_cassettes" c.hook_into :webmock end VCR.use_cassette("example-dot-com-index") do Net::HTTP.get "www.example.com", "/" end
  • 15. Library support Test::Unit Minitest RSpec Cucumber VCR Webmock Fakeweb Faraday Excon Typhoeus
  • 16. RSpec RSpec.configure do |c| c.extend VCR::RSpec::Macros end describe "something" do use_vcr_cassette it "does something" do ... end end
  • 17. Cucumber VCR.cucumber_tags do |t| t.tag '@example-dot-com-index' t.tag '@example-dot-com-another-request' end Feature: VCR stuff @example-dot-com-index Scenario: Do something Given foo When bar Then baz
  • 18. Cassettes --- http_interactions: - request: method: get uri: http://example.com/ body: '' headers: {} response: status: code: 200 message: OK headers: Content-Type: - text/html;charset=utf-8 Content-Length: - '26' body: This is the response body http_version: '1.1' recorded_at: Tue, 01 Nov 2011 04:58:44 GMT recorded_with: VCR 2.0.0
  • 19. Request matching VCR.configure do |c| c.default_cassette_options = { match_requests_on: [:method, :uri]} end Also available: • :host • :path • :query • :body • :headers
  • 20. Ignoring requests VCR.configure do |c| c.ignore_request do |request| URI(request.uri).port == 7777 end c.ignore_hosts "foo.com", "bar.com" c.ignore_localhost = true end
  • 21. Summary Use Webmock (or Fakeweb) • For fine-grained control • If remote server isn’t available Use VCR • When record/replay is enough • For an easy life