WebMock stub_request无法正常工作

时间:2016-04-14 15:20:54

标签: ruby-on-rails ruby rspec webmock

在我的rails项目中,其中一个初始化者请求并从S3获取某些数据。

S3.buckets[CONFIG['aws']['cdn_bucket']].objects['object_name'].read

这打破了使用webmock gem

的rspec测试套件
WebMock.allow_net_connect!(:net_http_connect_on_start => true)



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

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 => {})

添加此存根不会修复错误。事实上,添加以下任何内容似乎没有任何改变:

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


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

我在这里失踪的是什么?错误消息中的详细标题似乎没有意义,允许S3的所有类型的请求

修改

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

,应该在哪里添加

1 个答案:

答案 0 :(得分:1)

在它上面睡觉之后,显然stub_request被添加到错误的地方。将它直接添加到初始化器可能已经解决了这个问题,但是这会破坏所有其他环境,因为gem webmock仅包含在测试环境中。

因此,将以下代码片段添加到修复此

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

S3.buckets[CONFIG['aws']['cdn_bucket']].objects['object_name'].read

如果包含gem,则会生成stub_request,否则只会继续运行。