![](/img/trans.png)
[英]How do I create a presigned link to a particular version of an object using the Ruby AWS SDK v2?
[英]How do I mock AWS SDK (v2) with rspec?
我有一個類使用aws-sdk-rails gem (它是aws-sdk-ruby v2上的包裝器)從SQS隊列讀取/處理消息。 如何模擬AWS調用以便我可以測試我的代碼而無需訪問外部服務?
communicator.rb :
class Communicator
def consume_messages
sqs_client = Aws::SQS::Client.new
# consume messages until the queue is empty
loop do
r = sqs_client.receive_message({
queue_url: "https://sqs.region.amazonaws.com/xxxxxxxxxxxx/foo",
visibility_timeout: 1,
max_number_of_messages: 1
})
break if (response.message.length == 0)
# process r.messages.first.body
r = sqs_client.delete_message({
queue_url: "https://sqs.region.amazonaws.com/xxxxxxxxxxxx/foo",
receipt_handle: r.messages.first.receipt_handle
})
end
end
end
我很難找到模擬AWS資源的示例。 我花了幾天時間搞清楚,並希望在Stack Overflow上分享我的結果以供后代使用。 我使用了rspec-mocks ( 雙打和驗證雙打) 。 這是問題中的communicator.rb
示例。
communicator_spec.rb :
RSpec.describe Communicator do
describe "#consume_messages" do
it "can use rspec doubles & verifying doubles to mock AWS SDK calls" do
sqs_client = instance_double(Aws::SQS::Client)
allow(Aws::SQS::Client).to receive(:new).and_return(sqs_client)
SQSResponse = Struct.new(:messages)
SQSMessage = Struct.new(:body, :receipt_handle)
response = SQSResponse.new([SQSMessage.new(File.read('data/expected_body.json'), "receipt_handle")])
empty_response = SQSResponse.new([])
allow(sqs_client).to receive(:receive_message).
and_return(response, empty_response)
allow(sqs_client).to receive(:delete_message).and_return(nil)
Communicator.new.consume_messages
end
end
end
AWS SDK已提供存根。 qv http://docs.aws.amazon.com/sdkforruby/api/Aws/ClientStubs.html了解更多信息(鏈接到官方文檔。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.