使用 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/'
作为网址创建存根不会使用基本身份验证,因为如果我这样做,即使我更改了凭据,我仍然可以访问我的模拟页面并且没有错误会被渲染。一些屏幕截图:
答案 0 :(得分:1)
WebMock和net-http-persistent之间存在不兼容性。
请参阅https://github.com/bblimke/webmock#connecting-on-nethttpstart
将WebMock.allow_net_connect!(:net_http_connect_on_start => true)
添加到您的测试设置中。
答案 1 :(得分:0)
根据documentation这应该有效:
stub_request(:get, "foo:bar@www.google.fr").
with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})