ruby-on-rails - 如何在 Rails 中的 Mechanize 上 stub HTTP 请求?

标签 ruby-on-rails ruby mechanize webmock

我有一些这样的代码库,我想使用 rspec 测试 favicon_href,但如你所愿,favicon_href 将调用页面函数,我知道我可以模拟页面函数,但在这个阶段我想模拟来自给定 url 的 HTTP 请求,所以我使用 WebMock gem 的语法来 stub HTTP 请求,但似乎 WebMock 与 Mechanize 不兼容,尽管我已经完成 stub ,但它总是在下面显示错误,任何人都知道如何解决它或任何 gem 都可以 stub HTTP要求 Mechanize ?

代码

  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

错误
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/")

   ============================================================

最佳答案

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


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

添加
WebMock.allow_net_connect!(:net_http_connect_on_start => true)
到您的测试设置。

关于ruby-on-rails - 如何在 Rails 中的 Mechanize 上 stub HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686203/

相关文章:

ruby - MongoDB + ruby : updating records in an iteration

ruby - 如何根据数组中对象的两个属性创建哈希?

Python Mechanize - 为什么我无法浏览此链接?

web-scraping - 多页表单(Nokogiri、Scrapy、其他?)

ruby-on-rails - Ruby ActiveRecord 模型中的级联删除?

ruby-on-rails - 在 Rails 应用程序中发送自动电子邮件

ruby-on-rails - 在计算机重启时运行 Rails 项目

python - 调试像 ruby​​ 这样的脚本语言

ruby-on-rails - HTML 解析 : How to find the image in the document, 哪个被大多数文本包围?

ruby-on-rails - Ruby on Rails : link-to using post method but parameters are in the URL