Webmock未注册的请求会导致我的测试失败

时间:2016-12-17 08:32:02

标签: rspec webmock

在我的spec_helper中,我有像这样的webmock设置:

WebMock.disable_net_connect!(allow_localhost: true)

RSpec.configure do |config|
  config.before(:each) do
    stub_request(:get, /cdn.\w+.io/).
      with(:headers => {'Accept-Encoding'=>'gzip', 'Access-Token'=> ENV['ACCESS_TOKEN'], 'Api-Key'=>ENV['API_KEY'], 'Expect'=>'', 'User-Agent'=>'Typhoeus - https://github.com/typhoeus/typhoeus'}).
      to_return(:status => 200, :body => "", :headers => {})
  end
end

现在,当我使用bundle exec rspec spec/stack_client_query_spec.rb单独运行此测试时,它会通过。

  describe "can query for entries by asking for a content_type" do
    it "returns a Typhoeus response with queried with a content_type" do
      response = create_client.content_type(content_type_uid).get
      expect(response).to be_instance_of(Typhoeus::Response)
    end
  end

但是当我使用bundle exec rspec运行完整的测试套件时,相同的测试会以此输出爆炸:

Failure/Error:
       response = Typhoeus::Request.new(
         endpoint,
         headers: { api_key: headers[:api_key], access_token: headers[:access_token],
         accept_encoding: "gzip" }
       ).run

     WebMock::NetConnectNotAllowedError:
       Real HTTP connections are disabled. Unregistered request: GET http://cdn.mycustom.domain/v3/content_types/shirts/entries/ with headers {'Accept-Encoding'=>'gzip', 'Access-Token'=>'bltbdc42da30987971c', 'Api-Key'=>'blt1c501b5fa4b64377', 'Expect'=>'', 'User-Agent'=>'Typhoeus - https://github.com/typhoeus/typhoeus'}

       You can stub this request with the following snippet:

       stub_request(:get, "http://cdn.mycustom.domain/v3/content_types/shirts/entries/").
         with(:headers => {'Accept-Encoding'=>'gzip', 'Access-Token'=>'bltbdc42da30987971c', 'Api-Key'=>'blt1c501b5fa4b64377', 'Expect'=>'', 'User-Agent'=>'Typhoeus - https://github.com/typhoeus/typhoeus'}).
         to_return(:status => 200, :body => "", :headers => {})

       registered request stubs:

       stub_request(:get, "/cdn.\w+.io/").
         with(:headers => {'Accept-Encoding'=>'gzip', 'Access-Token'=>'bltbdc42da30987971c', 'Api-Key'=>'blt1c501b5fa4b64377', 'Expect'=>'', 'User-Agent'=>'Typhoeus - https://github.com/typhoeus/typhoeus'})

似乎早期的测试是覆盖请求域或其他东西。我不确定为什么!?我究竟做错了什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

看起来你已经存根了

stub_request(:get, /cdn.\w+.io/)

但实际的请求是

http://cdn.mycustom.domain/

您可以将存根更改为

stub_request(:get, /cdn.\w+.domain/)