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

Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshare
tomcopeland
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
Cloudflare
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 

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 tossug
clkao
 
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
Gosuke Miyashita
 
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
KMS Technology
 

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

Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test community
Kerry 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
 
Background processing
Background processingBackground processing
Background processing
Kerry 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

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
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
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
 
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
 
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...
 
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...
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

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