我试着把WebMock.disable_net_connect!
放在很多地方,但正如上次测试中建议的那样,我把它放在spec_helper.rb
中,如下所示:
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
我的规格如下:
describe Client do
describe '#get_something' do
context 'when post params are valid' do
it 'returns a response' do
request = stub_request(:post, 'https://myurl.com')
.to_return(my_response)
result = client.get_something(params)
expect(WebMock).to have_requested(:post, 'https://myurl.com')
end
end
end
end
嗯,当然是我的客户打来的电话:
class Client
def get_something(params)
RestClient.post @url, params
end
end
它失败,并显示以下消息:
Failure/Error: end
The request GET https://myurl.com/ was expected to execute 1 time but it executed 0 times
The following requests were made:
No requests were made.
============================================================
我使用的是rails 4.1.8、rspec 3.1.7、rsspec rails 3.1.0和webmock 1.8.11。现在,我正在创建一个http_client的mock来让事情正常工作,但是,如果有任何帮助,我们将不胜感激!如果你需要更多信息,请告诉我!
您应该使用以下内容:
WebMock.allow_net_connect!
或者,你也可以做
WebMock.disable_net_connect(allow: ['https://myurl.com'])
如WebMock的文档所示:
WebMock.allow_net_connect!
stub_request(:any, "www.example.com").to_return(:body => "abc")
Net::HTTP.get('www.example.com', '/') # ===> "abc"
在对外部主机进行api调用之前放这两行为我解决了这个问题
WebMock.disable!
WebMock.disable_net_connect!
有关更多详细信息,请参阅:https://github.com/bblimke/webmock/issues/897