首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将HTTP请求存根到Rails中的机械化?

如何将HTTP请求存根到Rails中的机械化?
EN

Stack Overflow用户
提问于 2017-04-29 01:53:59
回答 1查看 511关注 0票数 0

我有一些这样的代码库,我想使用rspec测试favicon_href,但正如你所喜欢的,favicon_href会调用页面函数,我知道我可以模拟页面函数,但在这个阶段,我想模拟来自给定url的HTTP请求,所以我使用WebMock gem的语法来存根favicon_href请求,但似乎WebMock与机械化不兼容,尽管我重新做了存根,但它总是在下面显示错误,有人知道如何解决它或任何gem可以在机械化上存根HTTP请求吗?

代码

代码语言:javascript
复制
  def favicon_href
    @favicon_href ||= 
      begin
        page.at(FAVICON_DOM).attributes['href'].value # finding <link> elements
      rescue Exception
        '/favicon.ico' # there are some situation the favicon's not <link>'
      end
  end

  def page
    @page ||= mechanize.get(url)
  end

  def mechanize
    @mechanize ||= Mechanize.new
  end

错误

代码语言:javascript
复制
Failure/Error: @page ||= mechanize.get(valid_url(url))

 WebMock::NetConnectNotAllowedError:
   Real HTTP connections are disabled. Unregistered request: GET https://tsaohucn.wordpress.com/ with headers {'Accept'=>'*/*', 'Accept-Charset'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Encoding'=>'gzip,deflate,identity', 'Accept-Language'=>'en-us,en;q=0.5', 'Connection'=>'keep-alive', 'Host'=>'tsaohucn.wordpress.com', 'Keep-Alive'=>'300', 'User-Agent'=>'Mechanize/2.7.5 Ruby/2.3.1p112 (http://github.com/sparklemotion/mechanize/)'}

   You can stub this request with the following snippet:

   stub_request(:get, "https://tsaohucn.wordpress.com/").
     with(headers: {'Accept'=>'*/*', 'Accept-Charset'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Encoding'=>'gzip,deflate,identity', 'Accept-Language'=>'en-us,en;q=0.5', 'Connection'=>'keep-alive', 'Host'=>'tsaohucn.wordpress.com', 'Keep-Alive'=>'300', 'User-Agent'=>'Mechanize/2.7.5 Ruby/2.3.1p112 (http://github.com/sparklemotion/mechanize/)'}).
     to_return(status: 200, body: "", headers: {})

   registered request stubs:

   stub_request(:get, "https://tsaohucn.wordpress.com/").
     with(headers: {'Accept'=>'*/*', 'User-Agent'=>'Ruby'})
   stub_request(:any, "http://api.stripe.com/")
   stub_request(:any, "/api.stripe.com/")

   ============================================================
EN

回答 1

Stack Overflow用户

发布于 2017-08-22 00:05:58

WebMock和net-http-persistent之间存在不兼容。

请参阅https://github.com/bblimke/webmock#connecting-on-nethttpstart

添加

WebMock.allow_net_connect!(:net_http_connect_on_start => true)

到你的测试设置中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43686203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档