【问题标题】:Can't mock website with Basic Authentication无法使用基本身份验证模拟网站
【发布时间】:2014-11-13 16:33:22
【问题描述】:

使用 RubyMechanizeRSpecWebmock,我无法使用基本身份验证模拟网站,我的应用一直告诉我我有一个未注册的存根。

存根

stub_request(:get, "http://foo:bar@google.fr:80/").
     with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
     to_return(:status => 200, :body => "", :headers => {})

Net::HTTP.start('www.google.fr') {|http|
  req = Net::HTTP::Get.new('/')
  req.basic_auth 'foo', 'bar'
  http.request(req)
}

在应用中

url = 'http://www.google.fr'
agent = Mechanize.new 
agent.add_auth(url, 'foo', 'bar')
agent.get(url)

我在运行agent.get(url)时遇到的问题

(rdb:1) agent.get(url)
*** WebMock::NetConnectNotAllowedError Exception: Real HTTP connections are disabled.     Unregistered request: GET http://www.google.fr/ 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'=>'www.google.fr', 'Keep-Alive'=>'300', 'User-Agent'=>'Mechanize/2.7.3 Ruby/1.9.3p194 (http://github.com/sparklemotion/mechanize/)'}

You can stub this request with the following snippet:

stub_request(:get, "http://www.google.fr/").
  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'=>'www.google.fr', 'Keep-Alive'=>'300', 'User-Agent'=>'Mechanize/2.7.3 Ruby/1.9.3p194 (http://github.com/sparklemotion/mechanize/)'}).
  to_return(:status => 200, :body => "", :headers => {})

registered request stubs:

stub_request(:get, "http://foo:bar@www.google.fr/").
with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'})

几点:

  • 'http://foo:bar@google.fr/' 分配给url 确实 两者都不起作用(如果它仍然起作用,那将非常难看)。
  • 最后但并非最不重要的一点是,使用http://www.google.fr/' 作为 url 创建存根不会使用基本身份验证,因为如果我这样做,即使我更改了凭据,我仍然可以访问我的模拟页面并且不会出现错误渲染。

部分截图:

【问题讨论】:

    标签: ruby rspec mocking mechanize basic-authentication


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      根据documentation,这应该可以工作:

      stub_request(:get, "foo:bar@www.google.fr").
           with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
           to_return(:status => 200, :body => "", :headers => {})
      

      【讨论】:

      • 你在那里缺少www,但无论如何,它也不起作用image.noelshack.com/fichiers/2014/46/1415901709-lulzc.png谢谢anwyays
      • 很奇怪。我在第一篇文章中添加了一些屏幕截图,以展示发生在我身上的事情。
      • @sidney,抱歉我因为Net::HTTP.start('www.google.fr') {|http| 而感到困惑(它不是存根的一部分——它是显示存根有效的实际调用——你可以安全地删除它)。看来您的问题是 mechanize 和 webmock 之间存在某种不兼容,例如here
      猜你喜欢
      • 2013-05-30
      • 2018-09-27
      • 2019-06-26
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多