Skip to content

Instantly share code, notes, and snippets.

@CoffeeAndCode
Created February 25, 2013 04:46
Show Gist options
  • Save CoffeeAndCode/5027800 to your computer and use it in GitHub Desktop.
Save CoffeeAndCode/5027800 to your computer and use it in GitHub Desktop.
Mocking web requests when running specs in Guard only. If you run them through rspec (without setting the RSPEC_ENV environment variable to "guard") it will make the full web request.
guard 'rspec', :env => {'RSPEC_ENV' => 'guard'} do
# ...
end
require 'spec_helper'
describe SomeSpec do
describe '#method' do
it 'retrieves results when searching for a last name',
:webmock => 'spec/mocks/some-mock.html' do
response = Net::HTTP.get("www.example.com", "/")
response.content.should include("some string)
end
end
end
require 'webmock/rspec'
RSpec.configure do |config|
# ...
config.before(:suite) do
if ENV['RSPEC_ENV'] == 'guard'
WebMock.disable_net_connect!
else
WebMock.allow_net_connect!
end
end
config.around(:each) do |test|
if ENV['RSPEC_ENV'] == 'guard' and test.metadata[:webmock]
stub_request(:any, 'http://www.example.com').
to_return(
:body => File.new(test.metadata[:webmock]),
:headers => {
'Content-Type' => 'text/html; charset=UTF-8'
}
)
end
test.run
if ENV['RSPEC_ENV'] == 'guard' and test.metadata[:webmock]
WebMock.reset!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment