Lifestyle hooks always execute before traits

I am trying to create a user before every test:

trait('DatabaseTransactions')

beforeEach(async () => {
  await User.create({
    email: 'test@test.com',
    password: 'test',
  })
})

The problem is DatabaseTransactions is executed AFTER the user create so it doesn’t roll back for the next test at the right moment.

My solution was to include the code from DatabaseTransactions inside the beforeEach:

beforeEach(async () => {
  await use('Database').beginGlobalTransaction()
  await User.create({
    email: 'test@test.com',
    password: 'test',
  })
})

afterEach(() => {
  use('Database').rollbackGlobalTransaction()
})

Can you suggest a better solution or correct where I’m going wrong here. Thanks!

2 Likes

I don’t think there is any way for database transactions to know whether your hooks will be executed first or not. Infact the DatabaseTransaction trait itself uses these lifecycle hooks to create and rollback transactions.

So the only way is to not use that trait and manually bind it the way you are doing

Virk

Database setup/teardown is a standard necessity around every test. Does it make sense to have the trait approach be made compatible with Suite/Group hooks, or to modify the runner to have a beforeEach (Runner._stack.beforeEach) which is automatically copied onto each Suite/Group hooks?