【问题标题】:RSpec: Can we configure an expectation to return two different value? I want to test retry mechanismRSpec:我们可以配置一个期望返回两个不同的值吗?我想测试重试机制
【发布时间】:2021-06-04 00:00:36
【问题描述】:

所以我的应用程序中有一个重试规则。我想使用 rspec 进行测试。

当我在没有传递账户 ID 的情况下调用服务时,它应该给我 false,当传递账户 ID 时,它应该给我 true。

我正在尝试这段代码

options = {
  email: 'dev@dev.com'
}
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)

但这对我不起作用。

【问题讨论】:

    标签: ruby ruby-on-rails-3 rspec


    【解决方案1】:

    所以我想出了一个方法来做到这一点..

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

    【讨论】:

      【解决方案2】:

      尝试重写为:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-06
        • 1970-01-01
        • 2022-12-10
        • 2011-10-18
        • 2015-08-28
        • 2022-08-22
        • 1970-01-01
        相关资源
        最近更新 更多