Isolated tests running in their own transactions #759
-
Looking at the sqlx-postgres example as well as the testing example, it feels like it should be possible to have the same app and handlers accept either a sqlx Pool or Transaction object as the extension layer depending on context. In my case I would like to use a pool as the extension layer and have it be extracted to a connection in the handler (just as in the sqlx-postgres example) when running the app. But when testing, I would like to be able to use the same exact app and handler, but send it a transaction object instead where multiple entries in the database might have been created before making the request such that the handler also works inside the same transaction object as the one in the test. This way I can test against a real database but have each test isolated in their own transaction. I'm having problems achieving this, is this something that could be done? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
I don't think thats possible since extractors (things that implement Also, in general I would strongly recommend against wrapping each test in a transaction. I've attempted to do something like that in the past but kept running into issues, like the one you're facing. Instead I would recommend giving each test its own totally separate database. This is how I do it at work and it works great. We basically have some test helpers that creates a database with a random name, runs the migrations, and automatically removes the database when the test ends (via a |
Beta Was this translation helpful? Give feedback.
I don't think thats possible since extractors (things that implement
FromRequest
) most be fully owned. That is, they cannot contain borrowed data.sqlx::Transaction
borrows the connection so it cannot be accessed via an extractor. I'm not very familiar with sqlx so dunno if there is a workaround.Also, in general I would strongly recommend against wrapping each test in a transaction. I've attempted to do something like that in the past but kept running into issues, like the one you're facing. Instead I would recommend giving each test its own totally separate database. This is how I do it at work and it works great. We basically have some test helpers that creates a database with a random…