aws/aws-sdk-ruby

stub_responses function in Dynamodb, how can I pass query when stub?

namdv-1375 opened this issue · 4 comments

Describe the issue

I'm having a problem when my code uses get_item multiple times. However, if I write the test this way, every call to get_item will return the same data:

stub_dynamodb_client = Aws::DynamoDB::Client.new(stub_responses: true)
stub_dynamodb_client.stub_responses(:get_item, item: {"id" => 1})

How can i differentiate each time get_item to assign data to them differently? example:
first time: stub_dynamodb_client.stub_responses(:get_item, item: {"post_id" => 1})
second time: stub_dynamodb_client.stub_responses(:get_item, item: {"comment_id" => 2})
Pls, help me. Thankssss

Links

https://docs.aws.amazon.com/sdk-for-ruby/v2/api/Aws/ClientStubs.html#stub_responses-instance_method

Hi! You could do that as follows:

stub_dynamodb_client.stub_responses(
   :get_item,
  [
    { item: {"post_id" => 1 } },
    { item: {"comment_id" => 2 } },
  ],
)

To demostrate via repl:

[13] pry(Aws)> stub_dynamodb_client.get_item(table_name: '', key: {})           
[Aws::DynamoDB::Client 200 0.000822 0 retries] get_item(table_name:"foo",key:{})  
=> #<struct Aws::DynamoDB::Types::GetItemOutput item={"post_id"=>0.1e1}, consumed_capacity=nil>
[14] pry(Aws)> 
[14] pry(Aws)> stub_dynamodb_client.get_item(table_name: '', key: {})           
[Aws::DynamoDB::Client 200 0.000596 0 retries] get_item(table_name:"foo",key:{})  
=> #<struct Aws::DynamoDB::Types::GetItemOutput item={"comment_id"=>0.2e1}, consumed_capacity=nil>

I noticed that the linked docs for V2. Here's a link to V3 incase you are using that version.

The last section in the documentation, noted as "Stubbing Multiple Responses" expands on the multiple stub responses so I suggest checking that out. Hope this helps!

@jterapin wow, thanks you <3

This issue is now closed. Comments on closed issues are hard for our team to see.
If you need more assistance, please open a new issue that references this one.

I believe also instead of an array you can pass multiple hash arguments.