繁体   English   中英

Net :: HTTP.new(url.host,url.port)的存根结果

[英]Stubbing result of Net::HTTP.new(url.host, url.port)

我有一个调用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

查看webmock-听起来像它可以完全满足您的要求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM