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!

1 Like

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