Webmock and VCR are tools for stubbing and recording HTTP requests in tests. Webmock allows fine-grained control over stubbing but requires the remote server, while VCR records and replays requests without the server through cassettes. The document provides information on setting up and using both tools to stub or record HTTP requests in different testing frameworks for reliable and isolated tests.
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
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