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.
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))
according to https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/Errors/ServiceError.html#initialize-instance_method
the three arguments are
The message
is where you can add your own information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With