Net::HTTP.new(google_url.host, google_url.port) を呼び出す関数があり、テストのために結果をスタブする方法を見つけようとしています。基本的に、テストを実行するたびに Google URL 短縮サービスを実行したくありません。
def shorten_url(long_url)
google_url = URI.parse("https://www.googleapis.com/urlshortener/v1/url")
data = JSON.generate({"longUrl" => "#{long_url}"})
header = {"Content-Type" => "application/json"}
http = Net::HTTP.new(google_url.host, google_url.port)
http.use_ssl = true
short_url = ""
res = http.request_post(google_url.path, data, header)
jsonResponse = JSON.parse(res.body)
short_url = jsonResponse["id"]
end
基本的に、その関数の結果を設定できるようにしたいです。
私は次のようなことを試しました:Net::HTTP.any_instance.stubs(:HTTP.new).returns("www.test.com")
しかし、それを機能させる方法がわかりません。
class HTTP < Protocol
....
# Creates a new Net::HTTP object.
# If +proxy_addr+ is given, creates an Net::HTTP object with proxy support.
# This method does not open the TCP connection.
def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
h = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
h.instance_eval {
@newimpl = ::Net::HTTP.version_1_2?
}
h
end
....
end