Running tests within a transaction
See original GitHub issueA common pattern for testing code in the Ruby world (using RSpec) is to run each of your app’s tests within a transaction, and then rollback the transaction once the test is done. That way each test is run in an isolated environment and isn’t filling up a db with junk.
Is there a way to do this with Knex? I’ve spent a few hours trying to make it work with mocha. The following don’t seem to work:
beforeEach(function (done) {
knex.raw("start transaction").then(function () {
done();
});
});
afterEach(function (done) {
knex.raw("rollback").then(function () {
done();
});
});
or
var trx;
beforeEach(function (done) {
knex.transaction(function (newTrx) {
trx = newTrx;
done();
});
});
afterEach(function (done) {
trx.rollback().then(function () {
done();
});
});
I apologize if this question is naïve but I’m new to knex.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:2
- Comments:10 (3 by maintainers)
Top Results From Across the Web
Don't Use @Transactional in Tests - DEV Community
@Transactional enables undesired behaviors that produce false negatives in our test suite, which can impact the confidence developers have to ...
Read more >10.3 Integration testing - Spring
Indicates that the annotated public void method should be executed before a transaction is started for test methods configured to run within a...
Read more >Testing Transactions Example - Apache TomEE
This example shows use of @PersistenceContext to have an EntityManager with an TRANSACTION persistence context injected into a @Stateful bean using the @ ......
Read more >Programmatic Transactions in the TestContext Framework
In this article, we'll see how to programmatically interact with automatic transactions set up by Spring in transactional tests. 2.
Read more >How does @Transactional work on test methods?
@Transactional spans the transaction for entire test method, so if you use some dao (like in your case) that transaction will be rolledback ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Of course, the instant after I post this I figure it out. The first example I gave above worked, but I needed to set the connection’s pool to
{ min: 1, max: 1 }
since, I assume, the transaction is only valid on one connection and therefore all queries need to go over that single connection.@JonAbrams you have to take care that all queries that are executed during the test are run within this transaction.