如何使用 RSpec 控制器规范触发并发请求?

Vin*_*sil 5 concurrency rspec ruby-on-rails

我尝试使用线程和 RSpec 同时触发 5 个请求,但这给了我一个AbstractController::DoubleRenderError错误。我认为 RSpec 正在为请求共享相同的“上下文”。

context 'when the request is duplicated' do
  it 'blocks duplicate requests' do
    expect{

      threads = 5.times.map do
        Thread.new { post :checkout }
      end
      threads.map(&:join)

    }.to change{
      PaymentTransaction.count
    }.by(1)
  end
end
Run Code Online (Sandbox Code Playgroud)

有没有办法使用 RSpec 控制器测试来测试并发请求,而不会引发此类异常,也不共享相同的“环境”?

Vin*_*sil 3

RSpec 似乎对此没有官方解决方案。为了解决这个问题,我拯救了AbstractController::DoubleRenderError线程内的异常。这解决了它,因此它不是最优雅的解决方案。

context 'when the request is duplicated' do
  it 'blocks duplicate requests' do
    expect{

      threads = 5.times.map do
        Thread.new do
          post :checkout
        rescue AbstractController::DoubleRenderError
        end
      end
      threads.map(&:join)

    }.to change{
      PaymentTransaction.count
    }.by(1)
  end
end
Run Code Online (Sandbox Code Playgroud)