Database Tests
By default, your tests are are not ran in isolation from a database point of view. It means that your local database will be modified any time you run your tests and won't be rollbacked at the end of the tests. While this behaviour might be fine in most case you can learn below how to configure your tests cases to reset the database after each test.

Resetting The Database After Each Test

If you want to have a clean database for each test you must subclass the TestCase class with DatabaseTransactions class. Then all your tests will run inside a transaction so any data you create will only exist within the lifecycle of the test. Once the test completes, your database is rolled back to its previous state. This is a perfect way to prevent test data from clogging up your database.
1
from masonite.tests import TestCase, DatabaseTransactions
2
3
class TestSomething(TestCase, DatabaseTransactions):
4
5
connection = "testing"
6
7
def test_can_create_user(self):
8
User.create({"name": "john", "email": "john6", "password": "secret"})
Copied!
Note that you can define the connection that will be used during testing. This will allow you to select a different database that will be used for testing. Here is a standard exemple of database configuration file that you can use.
1
# config/database.py
2
DATABASES = {
3
"default": "mysql",
4
"mysql": {
5
"host": "localhost",
6
"driver": "mysql",
7
"database": "app",
8
"user": "root",
9
"password": "",
10
"port": 3306
11
}
12
"testing": {
13
"driver": "sqlite",
14
"database": "test_database.sqlite3",
15
},
16
}
Copied!

Available Assertions

Masonite provides several database assertions that can be used during testing.

assertDatabaseCount

Assert that a table in the database contains the given number of records.
1
self.assertDatabaseCount(table, count)
Copied!
1
def test_can_create_user(self):
2
User.create({"name": "john", "email": "john6", "password": "secret"})
3
self.assertDatabaseCount("users", 1)
Copied!

assertDatabaseHas

Assert that a table in the database contains records matching the given query.
1
self.assertDatabaseHas(table, query_dict)
Copied!
1
self.assertDatabaseCount("users", {"name": "John"})
Copied!

assertDatabaseMissing

Assert that a table in the database does not contain records matching the given query.
1
self.assertDatabaseMissing(table, query_dict)
Copied!
1
self.assertDatabaseMissing("users", {"name": "Jack"})
Copied!

assertDeleted

Assert that the given model instance has been deleted from the database.
1
user=User.find(1)
2
user.delete()
3
self.assertDeleted(user)
Copied!

assertSoftDeleted

Assert that the given model instance has been soft deleted from the database.
1
self.assertSoftDeleted(user)
Copied!
Last modified 2mo ago