ruby - 无法使用基本身份验证模拟网站

标签 ruby rspec mocking mechanize basic-authentication

使用 Ruby、Mechanize、RSpec 和 Webmock,我无法使用基本身份验证模拟网站,我的应用程序一直告诉我我有一个未注册的 stub 。

stub :

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/' 创建一个 stub 因为 url 不会使用基本身份验证,因为如果我这样做,即使我更改了凭据,我仍然可以访问我的模拟页面并且不会呈现任何错误。

  • 部分截图:

    enter image description here
    enter image description here

    最佳答案

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

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

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

    关于ruby - 无法使用基本身份验证模拟网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26913764/

    相关文章:

    ruby - 在 Ruby 中关闭 SSL 证书验证

    ruby-on-rails - 创建 has_one 关联错误 Rails 4

    ruby - 如何解决由于 Ruby 中的垃圾回收引起的偶发性崩溃

    ruby - 更改 Ruby 对象的状态会更改其他类成员吗?

    ruby-on-rails - RSpec 功能规范找不到 Rails 引擎的路由

    python - 如何使用pytest测试一个方法是否被调用

    ruby-on-rails - Rspec - stub 模块方法

    ruby-on-rails - 在验收规范中测试或不测试什么?

    testing - Flutter:如何模拟 Bloc

    java - 模拟Mvc。如何在junit测试中涉及自定义对象