Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jspillers/a1eda91efb931b0eca7c to your computer and use it in GitHub Desktop.
Save jspillers/a1eda91efb931b0eca7c to your computer and use it in GitHub Desktop.
Sandbox test to get VCR, WebMock, and "real" http all working side by side in the same spec suite
require 'rubygems'
require 'rspec'
require 'webmock'
require 'vcr'
require 'pry'
# in a Rails app, this would be in an initializer
WebMock.disable_net_connect!(
allow_localhost: true,
net_http_connect_on_start: true
)
VCR.configure do |config|
config.cassette_library_dir = "vcr_cassettes"
config.hook_into :webmock # or :fakeweb
config.configure_rspec_metadata!
config.before_http_request(:stubbed?) do |request|
#binding.pry
end
end
class WebMockStubs
extend WebMock::API
def self.stub_all!
stub_request(:get, /google.com/).to_return(body: 'Stubbed by WebMock!')
end
end
RSpec.configure do |config|
config.around(:each) do |example|
if example.metadata[:real_http]
WebMock.disable!
elsif example.metadata[:vcr]
WebMock.enable!
WebMock.reset!
VCR.turn_on!
else
WebMock.enable!
WebMockStubs.stub_all!
VCR.turn_off!
end
example.run
end
end
RSpec.describe 'Stubbing with WebMock and VCR in the same suite' do
context 'Stubbed by VCR', :vcr do
let(:response) {
Net::HTTP.get_response(URI('http://www.google.com'))
}
it 'returns a 200 response' do
expect(response.code).to eql('200')
end
it 'is stubbed by VCR' do
expect(response.body).to include(
"Search the world's information, including webpages, images, videos and more"
)
end
end
context 'Stubbed by WebMock by default' do
let(:response) {
Net::HTTP.get_response(URI('http://www.google.com'))
}
it 'returns a 200 response' do
expect(response.code).to eql('200')
end
it 'is stubbed by WebMock' do
expect(response.body).to eql('Stubbed by WebMock!')
end
end
context 'Not stubbed by anything', :real_http do
let(:response) {
Net::HTTP.get_response(URI('http://www.google.com'))
}
it 'returns a 200 response' do
expect(response.code).to eql('200')
end
it 'makes a real http request' do
expect(response.body).to include(
"Search the world's information, including webpages, images, videos and more"
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment