From 772ddc831cf1609810536cf3d40ffa71fdd9dd23 Mon Sep 17 00:00:00 2001 From: Blake Williams Date: Thu, 6 Aug 2020 22:38:39 -0400 Subject: [PATCH] Fix middleware request uri race condition When writing a new Rails system test I ran into an issue where the browser would hang and not close, eventually failing the test due to pending requests. There were no clear pending requests and the requests mentioned were AJAX calls that should have been made several pages ago. I believe the cause is an AJAX call being cancelled almost immediately after it was initiated, but I'm not 100% positive. Code wise, it looks like the value of `env['REQUEST_URI']` that increments the counter is different from the `env['REQUEST_URI']` that's decremented in the `ensure` block. This resolves the issue by storing the `env['REQUEST_URI']` value in a variable so it will be consistent between counter calls. --- lib/capybara/server/middleware.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/capybara/server/middleware.rb b/lib/capybara/server/middleware.rb index 3dcc0043..504aaf87 100644 --- a/lib/capybara/server/middleware.rb +++ b/lib/capybara/server/middleware.rb @@ -53,14 +53,16 @@ module Capybara if env['PATH_INFO'] == '/__identify__' [200, {}, [@app.object_id.to_s]] else - @counter.increment(env['REQUEST_URI']) + request_uri = env['REQUEST_URI'] + @counter.increment(request_uri) + begin @extended_app.call(env) rescue *@server_errors => e @error ||= e raise e ensure - @counter.decrement(env['REQUEST_URI']) + @counter.decrement(request_uri) end end end