Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec - wrong number of arguments when raising error

So in my code I have this method I'm trying to test:

  # checks if a file already exists on S3
  def file_exists?(storage_key)
    begin
      s3_resource.bucket(@bucket).object(storage_key).exists?
    rescue Aws::S3::Errors::Forbidden => e
      false
    end
  end

Now I am trying to make two test cases - one for when the file exists, and one for when it doesn't.

Focusing on the failure case. I want to stub out the exists? to raise the Aws::S3::Errors::Forbidden error so that the file_exists? method will return false.

Here's what my test code looks like:

  it "returns false if the file doesn't already exist" do
    allow_any_instance_of(Aws::S3::Object).to receive(:exists?).and_raise(
      Aws::S3::Errors::Forbidden
    )
    expect(instance.file_exists?('foo')).to be false
  end

Running this test I see this:

   wrong number of arguments (given 0, expected 2)
   # ./lib/s3_client_builder.rb:48:in `file_exists?'

Really not clear what's going on here, since the file_exists? method definitely doesn't have an arity of 2 nor does the exists? method I'm stubbing.

To diagnose this, I put a breakpoint in the begin block. I try and run the <object>.exists? line and get the same error.

like image 903
max pleaner Avatar asked Nov 23 '16 23:11

max pleaner


2 Answers

It turns out the problem was with:

and_raise(
  Aws::S3::Errors::Forbidden
)

Running this shows the same error:

raise(Aws::S3::Errors::Forbidden)

What does work is this:

raise(Aws::S3::Errors::Forbidden.new(nil, nil))
like image 142
max pleaner Avatar answered Nov 16 '22 05:11

max pleaner


according to https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/Errors/ServiceError.html#initialize-instance_method

the three arguments are

  • context (Seahorse::Client::RequestContext)
  • message (String)
  • data (Aws::Structure) (defaults to: Aws::EmptyStructure.new)

The message is where you can add your own information.

like image 1
John Coote Avatar answered Nov 16 '22 07:11

John Coote