我无法让 Webmock 正常工作。我正在使用 HTTParty 发出 GET 请求。我想让以下请求返回错误:
require 'spec_helper'
require 'api_parser'
require 'httparty'
describe ApiParser do
describe "#get_data" do
it "returns data" do
stub_request(:get, "congress.api.sunlightfoundation.com").to_return(:status => [401, "Forbidden"])
puts HTTParty.get "http://congress.api.sunlightfoundation.com/bills/?history.enacted=true"
end
end
我在 spec_helper.rb 中添加了以下几行:
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
但它仍在调用实际的 API 并且没有被存根。我没有收到预期的 401 错误。我不确定这里有什么问题。spec_helper 是否遗漏了什么?
更新:我做了一些测试,看起来require api_parser
是导致这个问题的原因。当我删除它时,存根工作,但当我添加它时它停止工作。ApiParser 类是我使用 HTTParty 的地方。我修改了上面的测试直接使用HTTParty,而不是使用类中的方法。