WebMock 存根请求不工作

Sin*_*ein 6 ruby rspec ruby-on-rails webmock

在我的 Rails 项目中,其中一个初始化器请求并从S3.

S3.buckets[CONFIG['aws']['cdn_bucket']].objects['object_name'].read
Run Code Online (Sandbox Code Playgroud)

webmock这破坏了使用gem 的rspec 测试套件

WebMock.allow_net_connect!(:net_http_connect_on_start => true)
Run Code Online (Sandbox Code Playgroud)



当我尝试运行测试套件时出现以下错误

WebMock::NetConnectNotAllowedError

You can stub this request with the following snippet:

stub_request(:get, "https://bucket.s3.amazonaws.com/object_name").with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'', 'Authorization'=>'AWS AKxxxxxx:Hyxxxxxxxxxx', 'Content-Type'=>'', 'Date'=>'Thu, 14 Apr 2016 15:10:18 GMT', 'User-Agent'=>'aws-sdk-ruby/1.60.2 ruby/1.8.7 i686-darwin15.3.0'}).to_return(:status => 200, :body => "", :headers => {})
Run Code Online (Sandbox Code Playgroud)

添加此存根并不能修复错误。事实上,添加以下任何内容似乎都不会产生任何改变:

WebMock.stub_request(:any, /.*amazonaws.*/).with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'', 'Authorization'=>'AWS AKIxxxxxxxxxx:MSxxxxxxxx'}).to_return(:status => 200, :body => "stubbed response", :headers => {})
Run Code Online (Sandbox Code Playgroud)


WebMock.stub_request(:any, /.*amazonaws.*/).to_return(:status => 200, :body => "stubbed response", :headers => {})
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?错误消息中的详细标头在这里似乎没有意义,允许各种请求S3

编辑:

我刚刚注意到添加WebMock.disable!spec_helper也不会导致任何变化。我是否没有将存根添加到正确的位置?如果不在的话应该在哪里添加spec_helper

Sin*_*ein 3

睡了一觉后,很明显它stub_request被添加到了错误的地方。将其直接添加到初始化程序可以解决此问题,但这会破坏所有其他环境,因为 gemwebmock仅包含在测试环境中。

因此,将以下代码片段添加到脚本中修复了此问题

begin
  require 'webmock'
  WebMock.stub_request(:any, /testimonial/).to_return(:body => '')
rescue LoadError
end

S3.buckets[CONFIG['aws']['cdn_bucket']].objects['object_name'].read
Run Code Online (Sandbox Code Playgroud)

这使得stub_request如果宝石被包含在内,否则就会继续下去,就像什么也没发生一样。