Created
May 15, 2019 18:57
-
-
Save bitlather/9e7024cf5417ccea948321c5ddf0089d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# FROM: https://aws.amazon.com/blogs/developer/advanced-client-stubbing-in-the-aws-sdk-for-ruby-version-3/ | |
# | |
require 'rspec' | |
require 'aws-sdk-s3' | |
describe "Enhanced Stubbing Example Tests" do | |
let(:fake_s3) { {} } | |
let(:client) do | |
client = Aws::S3::Client.new(stub_responses: true) | |
client.stub_responses( | |
:create_bucket, ->(context) { | |
name = context.params[:bucket] | |
if fake_s3[name] | |
'BucketAlreadyExists' # standalone strings are treated as exceptions | |
else | |
fake_s3[name] = {} | |
{} | |
end | |
} | |
) | |
client.stub_responses( | |
:get_object, ->(context) { | |
bucket = context.params[:bucket] | |
key = context.params[:key] | |
b_contents = fake_s3[bucket] | |
if b_contents | |
obj = b_contents[key] | |
if obj | |
{ body: obj } | |
else | |
'NoSuchKey' | |
end | |
else | |
'NoSuchBucket' | |
end | |
} | |
) | |
client.stub_responses( | |
:put_object, ->(context) { | |
bucket = context.params[:bucket] | |
key = context.params[:key] | |
body = context.params[:body] | |
b_contents = fake_s3[bucket] | |
if b_contents | |
b_contents[key] = body | |
{} | |
else | |
'NoSuchBucket' | |
end | |
} | |
) | |
client | |
end | |
it "raises an exception when a bucket is created twice" do | |
client.create_bucket(bucket: "foo") | |
client.create_bucket(bucket: "bar") | |
expect { | |
client.create_bucket(bucket: "foo") | |
}.to raise_error(Aws::S3::Errors::BucketAlreadyExists) | |
expect(client.api_requests.size).to eq(3) | |
end | |
context "bucket operations" do | |
before do | |
client.create_bucket(bucket: "test") | |
end | |
it "can write and retrieve an object" do | |
client.put_object(bucket: "test", key: "obj", body: "Hello!") | |
obj = client.get_object(bucket: "test", key: "obj") | |
expect(obj.body.read).to eq("Hello!") | |
expect(client.api_requests.size).to eq(3) | |
expect(client.api_requests.last[:params]).to eq( | |
bucket: "test", | |
key: "obj" | |
) | |
end | |
it "raises the appropriate exception when a bucket doesn't exist" do | |
expect { | |
client.put_object( | |
bucket: "sirnotappearinginthistest", | |
key: "knight_sayings", | |
body: "Ni!" | |
) | |
}.to raise_error(Aws::S3::Errors::NoSuchBucket) | |
expect(client.api_requests.size).to eq(2) | |
end | |
it "raises the appropriate exception when an object doesn't exist" do | |
expect { | |
client.get_object(bucket: "test", key: "404NoSuchKey") | |
}.to raise_error(Aws::S3::Errors::NoSuchKey) | |
expect(client.api_requests.size).to eq(2) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment