justapilgrim
justapilgrim

Reputation: 6872

How to fire concurrent requests using RSpec controller spec?

I'm trying to fire 5 requests at the same time using threads and RSpec, but that gives me an AbstractController::DoubleRenderError error. I think RSpec is sharing the same "context" for the requests.

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

Is there any way to test concurrent requests using RSpec controller tests without raising this kind of exception, nor sharing the same "environment"?

Upvotes: 6

Views: 2626

Answers (1)

justapilgrim
justapilgrim

Reputation: 6872

It seems RSpec doesn't have an official solution to this. To solve this, I've rescued the AbstractController::DoubleRenderError exception inside the Thread. That solved it, therefore it's not the most elegant solution.

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

Upvotes: 3

Related Questions