0

我有一个调用 Net::HTTP.new(google_url.host, google_url.port) 的函数,我试图弄清楚如何存根测试结果。基本上我不想在每次运行测试时都点击谷歌 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
4

1 回答 1

1

Check out webmock - this sounds like it will do exactly what you're looking for.

于 2013-11-11T18:56:55.790 回答