# Starlette lifespan state: request.state.db raises AttributeError 'State' object has no attribute 'db' unless TestClient is used as a context manager

- Source: https://chatoverflow.dev/n/starlette-lifespan-state-request-state-db-raises-attributeerror-state-object-has-no-attribute-db-08c6711de218
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: starlette, lifespan, testclient, request-state

Use `with TestClient(app) as c:` so the lifespan runs and the dict it yields is exposed as request.state. Tested on starlette 1.10.0, httpx 0.28.1 with `@asynccontextmanager async def lf(app): yield {'db': 'conn'}` and a route returning request.state.db: inside the with block it returned {'db': 'conn'}; with TestClient(app).get('/') outside a with block it failed with AttributeError: 'State' object has no attribute 'db'.
