Skip to content

A free open source IT asset/license management system

Tests: Avoid truncation to improve test speed

Marcus Moore503002dff46a
diff --git a/.ai/rules/tests.md b/.ai/rules/tests.md
index 2754577414..4e863d35e5 100644
--- a/.ai/rules/tests.md
+++ b/.ai/rules/tests.md
@@ -24,3 +24,19 @@ Use `$this->actingAsForApi($user)` in API tests and `$this->actingAs($user)` in
## Feature and unit test placement
Feature tests live in `tests/Feature/`, grouped by the feature or resource under test. A resource with both API and web controllers splits its tests into `Api/` and `Ui/` subfolders matching the layer under test; cross-cutting feature-area suites stay flat in their folder. Unit tests live in `tests/Unit/`, grouped by the type under test (`Models/`, `Presenters/`, `Transformers/`...).
+
+## Avoid calling truncate() in tests — use delete() or forceDelete()
+
+Avoid using `Model::truncate()` or `DB::table(...)->truncate()` in a test. Use `Model::query()->delete()` (soft delete)
+or `Model::query()->forceDelete()` (hard delete) instead — both are DML and roll back normally.
+
+Why: TRUNCATE is DDL, and MySQL implicitly commits on DDL. That destroys the transaction `LazilyRefreshDatabase` wraps
+each test in. Laravel spots the dead transaction at teardown, clears `RefreshDatabaseState::$migrated`, and re-runs
+all migrations before the next test — roughly 10s per occurrence on MySQL. SQLite hides the problem entirely
+because its DDL is transactional, so this only shows up on a MySQL run.
+
+The same trap applies to any runtime DDL, notably `Schema::table()` — which is why creating a `CustomField` (its
+`created` hook does `ALTER TABLE assets`) is expensive on MySQL.
+
+Tell: the test that runs the DDL looks fast; the *next* test pays. A test suddenly reporting ~1,690 queries is paying
+for a re-migration.
diff --git a/tests/Unit/Importer/AssetImportTest.php b/tests/Unit/Importer/AssetImportTest.php
index d7123659b9..a9ddb56838 100644
--- a/tests/Unit/Importer/AssetImportTest.php
+++ b/tests/Unit/Importer/AssetImportTest.php
@@ -12,7 +12,7 @@ class AssetImportTest extends TestCase
{
public function test_uses_first_deployable_status_label_as_default_if_one_exists()
{
- Statuslabel::truncate();
+ Statuslabel::query()->forceDelete();
$pendingStatusLabel = Statuslabel::factory()->pending()->create();
$readyToDeployStatusLabel = Statuslabel::factory()->readyToDeploy()->create();
@@ -27,7 +27,7 @@ class AssetImportTest extends TestCase
public function test_uses_first_status_label_as_default_if_deployable_status_label_does_not_exist()
{
- Statuslabel::truncate();
+ Statuslabel::query()->forceDelete();
$statusLabel = Statuslabel::factory()->pending()->create();
@@ -41,7 +41,7 @@ class AssetImportTest extends TestCase
public function test_creates_default_status_label_if_one_does_not_exist()
{
- Statuslabel::truncate();
+ Statuslabel::query()->forceDelete();
$this->assertEquals(0, Statuslabel::count());