Skip to content

Instantly share code, notes, and snippets.

@bitlather
Created May 15, 2019 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitlather/9e7024cf5417ccea948321c5ddf0089d to your computer and use it in GitHub Desktop.
Save bitlather/9e7024cf5417ccea948321c5ddf0089d to your computer and use it in GitHub Desktop.
#
# 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