如何使用Minitest测试外部api的轮询?

时间:2018-05-24 14:08:40

标签: api ruby-on-rails-4 sidekiq yield

我试图嘲笑&存根BaseApi.authenticateBaseApi::TrackableJob(这是api请求)但是失败了。

module BaseApis
  class PollTrackableJobWorker
    include Sidekiq::Worker

    ...

    def perform(job_id, _invoice_id)
      BaseApi.authenticate(1) do
        response = BaseApi::TrackableJob.find(job_id).first

        case response['status']
        when 'done' then true
        when 'error' then Bugsnag.notify(response['errors'])
        when 'pending' || 'running' then raise EDocumentNotSentError
        end
      end
    end
  end
end

注意:

  1. 省略了与重试机制相关的代码。
  2. 我们使用mocha gem
  3. 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

事实证明,我过度思考并且yields方法是解决方案:

test 'status is done' do
  response = {
    'type'       => 'trackable_jobs',
    'id'         => '0b6ffad9177aeb594ad54af0',
    'status'     => 'done',
    'errors'     => nil
  }

  BaseApi.expects(:authenticate).with(1).yields
  BaseApi::TrackableJob.stubs(:find).returns([response])

  assert_equal(true, BaseApis::PollTrackableJobWorker.new.perform('xxx', 123))
end