【发布时间】:2014-11-13 16:33:22
【问题描述】:
使用 Ruby、Mechanize、RSpec 和 Webmock,我无法使用基本身份验证模拟网站,我的应用一直告诉我我有一个未注册的存根。
存根:
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