Rspec用于重试机制

时间:2018-03-26 10:32:15

标签: ruby-on-rails rspec rspec-rails rspec3 ruby-on-rails-5.1

我正在使用法拉第,我已经实现了一个按预期工作的重试机制,但我不明白如何在rspec上测试它。

以下是我的重试机制:

def perform(url:)
  max_retries = 3
  retry_count = 0
  delay = 1

  begin
    req = config_faraday
    response = req.get(url)
    JSON.parse(response.body)
  rescue Faraday::Error => err
    puts "Request failed. Retries left: #{max_retries - retry_count}"
    sleep delay += retry_count
    retry_count += 1
    retry if retry_count < max_retries
  ensure
    if retry_count == max_retries
      raise ApiError.new("Number of retries has been exhausted")
    end
  end
end

我不确定如何处理when api is not working

的情况

我是通过存档get请求并将retry_count设为最大值然后尝试点击请求来编写的:

  context 'Api is not working' do

    let(:retry_count){
      3
    }

    before do
      request = double(Faraday)
      allow(request).to receive(:get).and_raise(Faraday::Error)
    end

    it "raise error after retries" do
      expect(Products::Fetcher.perform(url: url)).to raise_error(Products::ApiError)
    end
  end

但是我收到了错误:

 Products::Fetcher Api is not working raise error after retries
     Failure/Error: expect(Products::Fetcher.perform(url: url)).to raise_error(Products::ApiError)
       expected Products::ApiError but was not given a block
     # ./spec/services/products/fetcher_spec.rb:34:in `block (3 levels) in <top (required)>'

2 个答案:

答案 0 :(得分:0)

很奇怪:你的测试不会测试perform的任何代码。这有时是好的,但在这种情况下,他们似乎没有测试除了你的存根之外的任何东西。

对于API测试,我建议查看像vcr这样的宝石。但这不会重现失败,然后重试然后成功。

要测试一下,从你展示的代码中,我会发送config_faraday来返回一个模拟对象,这会在调用get时引发错误两次并在第三次返回一个正文, 例如。

答案 1 :(得分:0)

Uncaught SyntaxError: Unexpected token (匹配器语法错误 正确的是:

raise_error

您的示例:

expect { raise StandardError }.to raise_error

因此正确的格式应为:

expect(Products::Fetcher.perform(url: url)).to raise_error(Products::ApiError)