Q41 of 48 · Cypress

Compare cy.session caching across specs vs per-spec session caching.

CypressSeniorcypresscy-sessionscalingsenior

Short answer

Short answer: Per-spec caching (default) re-runs login on the first test of each spec. `cacheAcrossSpecs: true` persists the session across the whole suite — log in once for the entire run. The trade-off: across-spec saves more time but requires confidence the cached state is genuinely shareable (no spec mutates auth-related data destructively).

Detail

Both modes share the same API; the difference is the cache lifetime.

Per-spec caching (cy.session(id, setupFn) without cacheAcrossSpecs):

  • The session is cached within a single spec file.
  • Each spec file's first cy.loginAs(...) call re-runs setup.
  • 200 specs × 4 roles → 200-800 logins (depending on roles per spec).
  • Safer when specs mutate user state in ways that might invalidate other specs' sessions.

cacheAcrossSpecs: true:

  • Cache persists for the entire cypress run execution.
  • One login per role across the whole suite.
  • 4 roles → 4 logins total. Massive time savings on large suites.
  • Requires the assumption that the cached session is valid for every spec that uses it.

When across-spec is risky:

  • Tests that destroy or modify the user (delete account, change password, log out from another session).
  • Tests that rotate auth tokens or invalidate sessions server-side.
  • Multi-tenant systems where the cached user might lose access to a tenant.

The mitigation: validate callbacks. Whatever the cache scope, a validate callback that pings /api/me and asserts 200 lets Cypress detect a stale session and re-run setup. With validate, cacheAcrossSpecs: true is robust:

cy.session('admin', loginFn, {
  cacheAcrossSpecs: true,
  validate() {
    cy.request({ url: '/api/me', failOnStatusCode: false })
      .its('status').should('eq', 200);
  },
});

A senior heuristic: default to cacheAcrossSpecs: true with a validate callback unless you have a specific reason not to. The 4-login total is the difference between a 30-minute and 50-minute suite.

A practical detail: with parallel CI, each shard maintains its own cache because they run in separate processes. Cross-spec caching helps within a shard, not across shards.

// WHAT INTERVIEWERS LOOK FOR

Knowing the cache lifetime difference, the `validate` callback as the safety net, and the parallel-CI implication that each shard caches independently.

// COMMON PITFALL

Using `cacheAcrossSpecs: true` without a validate callback and getting silent failures when tokens expire mid-run.