Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs about db:truncate and TestUtils.db().truncate() #196

Merged
merged 2 commits into from Oct 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 28 additions & 0 deletions content/guides/testing/introduction.md
Expand Up @@ -203,6 +203,8 @@ Make sure you have `@adonisjs/lucid` installed for the following examples to wor

### Migrating database

#### Reset database after each run cycle

You can migrate the database before running all the tests and roll it back after the tests. This can be done by registering the `TestUtils.db().migrate()` hook within the `tests/bootstrap.ts` file.

```ts
Expand All @@ -218,6 +220,32 @@ export const runnerHooks: Required<Pick<Config, 'setup' | 'teardown'>> = {
}
```

#### Truncate database after each run cycle

An alternative to the above approach is to truncate all tables in the database after each run cycle instead of rolling it back. This can be done by registering the `TestUtils.db().truncate()` hook within the `tests/bootstrap.ts` file.

```ts
// title: tests/bootstrap.ts
export const runnerHooks: Required<Pick<Config, 'setup' | 'teardown'>> = {
setup: [
() => TestUtils.ace().loadCommands(),
// highlight-start
() => TestUtils.db().truncate()
// highlight-end
],
teardown: [],
}
```

Before running your tests, the hook will migrate the database if necessary. After the tests are run, all the tables in your database will be kept but truncated.

So next time you run your tests, your database will be empty but will not need to be migrated again. This may be a better approach and will save you some time if you have a lot of migrations.

:::tip
Note that the hook internally calls the `node ace db:truncate` command that you can also run manually. Also, note that this command will truncate all tables **except** `adonis_schema` and `adonis_schema_versions` tables.
:::


### Seeding database
You can also run database seeders by calling the `TestUtils.db().seed()` method.

Expand Down