Search code examples
rubyamazon-web-servicesrspecaws-sdks3-bucket

AWS SDK : NoMethodError: undefined method `put_object' in Rspec Testing


Working with AWS SDK on S3 Buckets and testing with Rspec, I came across this error constantly even though I made a lot of changes.

Here's the code.

Flow.rb

require 'S3Ops.rb'
require 'aws-sdk'

def putzip(s3,bucket,instance)
  y=File.size('TestZip.zip')
  puts "File size of the test zip is #{ y.to_s}"
  File.open('TestZip.zip','rb') do |file|
    s3.put_object(bucket: bucket, key: instance+'/Test.zip', body: file)
  end
  result=@s3_bucket.list_objects({bucket: @bucket_name})
  z = result.contents[0].size
  puts 'File size of Uploaded file is ' + z.to_s
end

describe 'Test' do
  before(:all) do
    bucket_name = 'testbucket'
    instance_name = 'testinstance'
    s3 = S3Ops.new
    putzip(s3, bucket_name, instance_name)
  end

    **example tests**
end

S3Ops.rb

require 'aws-sdk'

class S3Ops
  def initialize
    @s3 = Aws::S3::Client.new(region: 'ap-southeast-1')
  end

**other functions**
end

Error

Failure/Error: s3.put_object(bucket: bucket, key: instance + '/Test.zip', body: file)    
NoMethodError:
   undefined method `put_object' for #<S3Ops:0x000000020707e0>

I even tried globalizing all variables to increase the scope and re-initializing s3 operations inside the function like this.

require 'S3Ops.rb'
require 'aws-sdk'

def putzip(s3,bucket,instance)
  y=File.size('TestZip.zip')
  puts "File size of the test zip is #{ y.to_s}"
  s3 = S3Ops.new
  File.open('TestZip.zip','rb') do |file|
    s3.put_object(bucket: bucket, key: instance+'/Test.zip', body: file)
  end
  result=@s3_bucket.list_objects({bucket: @bucket_name})
  z = result.contents[0].size
  puts 'File size of Uploaded file is ' + z.to_s
end

describe 'Test' do
  before(:all) do
    @bucket_name = 'testbucket'
    @instance_name = 'testinstance'
    @s3 = S3Ops.new
    putzip(@s3, @bucket_name, @instance_name)
  end

    **example tests**
end

Still it showed same error. What changes are necessary to correct the errors?

Edit

It works fine in example tests as shown below

it 'checks for zip' do
  result = @s3.list_objects(bucket: bucket)
  puts result.contents[0].key
end

Output: TestZip.zip


Solution

  • The way I was initiating S3Ops was wrong and had no return statement to give the pointer back to the Flow. Hence S3 connection was failing.

    I rectified it and its working now.