In my rails project, one of the initialisers requests and fetches certain data from S3
.
S3.buckets[CONFIG['aws']['cdn_bucket']].objects['object_name'].read
This breaks the rspec test suite which uses webmock
gem
WebMock.allow_net_connect!(:net_http_connect_on_start => true)
I get the following error when I try to run the test suite
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 => {})
Adding this stub does not fix the error. Infact, adding any of the following does not seem to make any change:
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 => {})
What is it that I am missing here? The detailed header in the error message does not seem to make sense here to allow all kinds of requests to S3
EDIT:
I just noticed that adding WebMock.disable!
to the spec_helper
also results in no change. Am I not adding the stub to the right place? Where should it be added if not in the spec_helper
?
After sleeping over it, it was clear that the stub_request
was being added to the wrong place. Adding it directly to the initialiser could have fixed this but that would have broken all other environments as the gem webmock
is included for test env only.
Hence adding the following code snippet to the script fixed this
begin
require 'webmock'
WebMock.stub_request(:any, /testimonial/).to_return(:body => '')
rescue LoadError
end
S3.buckets[CONFIG['aws']['cdn_bucket']].objects['object_name'].read
This makes a stub_request
if the gem is included else simply goes on as nothing happened.