3

我试图放在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、rspec-rails 3.1.0 和 webmock 1.8.11。现在,我正在创建一个 http_client 的模拟来让事情正常工作,但是,这里的任何帮助都将不胜感激!如果您需要更多信息,请告诉我!

4

1 回答 1

0

你应该改用这个:

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"
于 2016-03-31T05:38:18.243 回答