Test Transactions
Wrap each test in a transaction and roll back after — isolates tests from each other without truncating tables.
Wrap each test in a transaction and roll back after — isolates tests from each other without truncating tables.
-- Per-test transaction wrap (PHPUnit / pytest approach)
-- Before test: START TRANSACTION;
-- After test: ROLLBACK;
-- Benefits: fast, isolated, no fixture cleanup
-- Laravel: use DatabaseTransactions trait
use Illuminate\Foundation\Testing\DatabaseTransactions;
class OrderTest extends TestCase {
use DatabaseTransactions; // wraps each test in a transaction
public function test_order_creation(): void {
$order = Order::factory()->create();
$this->assertDatabaseHas("orders", ["id" => $order->id]);
} // rolled back automatically
}
DatabaseTransactions is faster than RefreshDatabase for read-write tests on existing data.