Fix flaky admin impersonation feature spec
What does this MR do and why?
Fixes the flaky examples in spec/features/admin/users/admin_impersonates_user_spec.rb. Full investigation summary https://gitlab.com/gitlab-org/quality/test-failure-issues/-/work_items/43497#note_3620462584
The race
SidebarsHelper reads the merge request counts with cached_only: true, which returns nil on a cache miss rather than running an expensive query. In test Rails.cache is a :null_store, so it always misses and user_counts.vue fires GET /api/v4/user_counts on every page load.
Impersonating calls warden.set_user, which sets renew: true. Rack deletes the old session from Redis and mints a new session ID. A user counts request still in flight carries the old cookie, misses, is handed a fresh anonymous session, and its Set-Cookie overwrites the valid one. The browser is then unauthenticated and DELETE /admin/impersonation fails CSRF verification.
The fix
Warm the count caches in a before hook so the counts ship in the page payload and the fetch is never made. This gives the test the warm-cache behaviour production normally has. COUNT_CACHE_VALIDITY_PERIOD is 24 hours, so on a real instance most page loads never make this request. The :null_store in test is what makes it fire every single time.
A guard asserts the caches are warm, so if cached_only: or the cache keys change, this fails with a clear message rather than quietly returning to flakiness.
References
How to set up and validate locally
- Green pipeline
🟢 - Run the spec locally a few times and confirm there are no flaky failures
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.