使用 Rspec 测试重试块

Testing a Retry bloc using Rspec

我正在尝试为故障转移端点机制编写测试。该函数的预期功能是调用主端点,如果成功则不重试,但如果失败则重试 3 次。如果在第 3 次尝试后失败,则对次要端点重复相同的操作。

def function
 with_retries(<fill params like handler, max tries etc>) do 
   call primary endpoint
  end
 rescue errors
  with_retries(<fill params like handler, max tries etc>) do 
   call secondary endpoint
  end              

欢迎任何想法!

我认为with_retires方法不需要在这个上下文中测试,因为它已经单独测试过了。但是恕我直言,当第一个端点 returns 出错时,测试次要端点被调用是合理的。

假设我们的方法是这样的

def function
  with_retries(<fill params like handler, max tries etc>) do 
    call_primary_endpoint
  end
rescue errors
  with_retries(<fill params like handler, max tries etc>) do 
    call_secondary_endpoint
  end 
end

然后我会写一个RSpec这样的期望

describe "#function" do
  subject { YourClass.new }

  before do
    # no need to test the actually endpoint implementation, we are only interested in the behavior
    allow(subject).to receive(:call_primary_endpoint).and_raise("ExpectedError")
    allow(subject).to receive(:call_secondary_endpoint).and_return(:expected_result)
  end

  it "calls secondary endpoint when the primary fails" do
    subject.function

    # Test that the primary endpoint is called max retry times (I assume 3 times)
    expect(subject).to have_received(:call_primary_endpoint)..exactly(3).times
    # Test that the secondary endpoint is called once
    expect(subject).to have_received(:call_secondary_endpoint).once
  end
end