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

时间:2013-11-11 18:50:58

标签: ruby-on-rails ruby

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

1 个答案:

答案 0 :(得分:1)

查看webmock - 听起来它会完全符合您的要求。