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

添加此 stub 并不能修复错误。事实上,添加以下任何一项似乎都没有任何改变:
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 => {})

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

编辑:

我只是注意到将 WebMock.disable! 添加到 spec_helper 也不会产生任何变化。我没有将 stub 添加到正确的位置吗?如果不在 spec_helper 中,应该在哪里添加?

最佳答案

睡了之后,很明显 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,否则会在没有发生任何事情的情况下继续运行。

关于ruby-on-rails - WebMock stub_request 不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36627434/

10-12 05:47