Skip to content

Instantly share code, notes, and snippets.

@ogawatti
Created April 14, 2015 02:59
Show Gist options
  • Save ogawatti/dfd66d211c2ea18c6d6b to your computer and use it in GitHub Desktop.
Save ogawatti/dfd66d211c2ea18c6d6b to your computer and use it in GitHub Desktop.
WebMock#enable! & reset! & disable!
require 'webmock'
require 'httpclient'
require 'excon'
require 'net/http'
module Mock
include WebMock::API
WebMock.allow_net_connect!
extend self
def on
WebMock.enable! #=> WebMockを有効化
stub_request(:any, "www.google.co.jp").to_return(
:body => "mock response",
:status => 200,
:headers => { 'Content-Length' => 13 }
) #=> stub登録
end
def off
WebMock.reset! #=> stub_requestで登録したStubがリセットされる
WebMock.disable! #=> WebMockを無効化
end
end
# == Mock.off
p "---------------------------------------"
res = Net::HTTP::Proxy(
ENV['PROXY_HOST'], ENV['PROXY_PORT'], ENV['PROXY_USER'], ENV['PROXY_PASS']
).get("www.google.co.jp", "/")
p res[0..50] #=> "<!doctype html><html itemscope=\"\" itemtype=\"http://"
res = HTTPClient.new.get "http://www.google.co.jp/"
p res.status #=> 200
p res.body[0..50] #=> "<!doctype html><html itemscope=\"\" itemtype=\"http://"
res = ::Excon.new("http://www.google.co.jp/", { proxy: ENV['HTTP_PROXY'] }).get(:path => "/")
p res.status #=> 200
p res.body[0..50] #=> "<!doctype html><html itemscope=\"\" itemtype=\"http://"
p "---------------------------------------"
Mock.on
res = ::Net::HTTP::Proxy(
ENV['PROXY_HOST'], ENV['PROXY_PORT'], ENV['PROXY_USER'], ENV['PROXY_PASS']
).get("www.google.co.jp", "/")
p res[0..50] #=> "mock response"
res = HTTPClient.new.get "http://www.google.co.jp/"
p res.status #=> 200
p res.body[0..50] #=> "mock response"
res = ::Excon.new("http://www.google.co.jp/", { proxy: ENV['HTTP_PROXY'] }).get(:path => "/")
p res.status #=> 200
p res.body[0..50] #=> "mock response"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment