簡體   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