Home > OS >  RSpec: Can we configure an expectation to return two different value? I want to test retry mechanism
RSpec: Can we configure an expectation to return two different value? I want to test retry mechanism

Time:09-17

So I have a retry rule in my application. I wanted to test that using rspec.

When I call service without passing account ID it should give me false and when account ID is passed it should give me true.

I am trying this code

options = {
  email: '[email protected]'
}
expect_any_instance_of(PaymentService::CreatePayment).to receive(:call)
                                                           .with(options)
                                                           .and_return(false)
options[:account_id] = 12345
expect_any_instance_of(PaymentService::CreatePayment).to receive(:call)
                                                           .with(options)
                                                           .and_return(true)

But this doesnt work for me.

CodePudding user response:

Try re-writing as:

invalid_options = {
  email: '[email protected]'
}
expect_any_instance_of(PaymentService::CreatePayment).to receive(:call)
                                                           .with(invalid_options)
                                                           .and_return(false)
valid_options = {
  email: '[email protected]',
  account_id: 12345
}
expect_any_instance_of(PaymentService::CreatePayment).to receive(:call)
                                                           .with(valid_options)
                                                           .and_return(true)

CodePudding user response:

So I have figured out a way to do this..

expect_any_instance_of(PaymentService::CreatePayment).to receive(:call).twice do |_, _, options|
  options[:account_id].present? ? true : false
end
  • Related