[Laravel] Testing model database table columns
One of the first things I do when setting up a new Laravel project is to create tests for my models. Through a series of posts on my blog, I will be putting up some of my most common model tests. Even if many people don't do this, I use these posts as references so that I don't need to open up previous projects to look for them.
This post will show you how to test the model columns to assert that they exist and match what you expect. These tests will help you keep track of all the columns that your model represents. When you have multiple migrations that add and remove columns to a table, it can become hard to keep track of all of the columns without checking the database. It gives me a nice place to look and see what columns are on a table in the codebase. One of the first things I do when I setup a new Laravel project is create tests for my models. Through a series of posts on my blog I will be putting up some of my most common model tests. Even if a lot of people don't do this I use these posts as references for me so that I don't need to open up previous projects to look for them.
- PHPUnit
- Pest
// tests/Models/UserTest.php
1use Tests\TestCase;2use Illuminate\Support\Facades\Schema;3use Illuminate\Foundation\Testing\RefreshDatabase;45class UserTest extends TestCase6{7 use RefreshDatabase;89 public function test_it_has_the_expected_columns()10 {11 $columns = [12 'id',13 'created_at',14 'updated_at',15 'name',16 'email',17 'email_verified_at',18 'password',19 'remember_token',20 ];2122 $this->assertEquals($columns, Schema::getColumnListing('users'));23 }24}
// tests/Models/UserTest.php
1use Tests\TestCase;2use Illuminate\Support\Facades\Schema;3use Illuminate\Foundation\Testing\RefreshDatabase;45uses(TestCase::class, RefreshDatabase::class);67it('has the expected columns', function () {8 expect(Schema::getColumnListing('users'))9 ->toBe([10 'id',11 'created_at',12 'updated_at',13 'name',14 'email',15 'email_verified_at',16 'password',17 'remember_token',18 ]);19});