Skip to content

Instantly share code, notes, and snippets.

@sagormax
Created September 12, 2024 00:24
Show Gist options
  • Save sagormax/ae9d90690b4922dc804f10318eef9543 to your computer and use it in GitHub Desktop.
Save sagormax/ae9d90690b4922dc804f10318eef9543 to your computer and use it in GitHub Desktop.
Laravel Model Unit Test
<?php
use App\Models\Deposit;
use Illuminate\Support\Facades\Schema;
describe('Deposit model', function () {
test('should match fillable properties', function () {
$fillable = [
'category_id',
'status',
'assigned_by',
'created_by',
];
$model = new Deposit;
$this->assertSame($fillable, $model->getFillable());
});
test('should has date cast properties', function () {
$model = new Deposit;
$this->assertArrayHasKey('date', $model->getCasts());
$this->assertSame('date', array_search('datetime', $model->getCasts()));
});
test('should has columns', function () {
$expectedColumns = [
"id",
"date",
"amount",
"details",
"created_at",
"updated_at",
"assigned_by",
];
$model = new Deposit;
$tableName = $model->getTable();
$actualColumns = Schema::getColumnListing($tableName);
$this->assertSame($expectedColumns, $actualColumns);
$this->assertEquals('datetime', Schema::getColumnType($tableName, 'date'));
$this->assertEquals('text', Schema::getColumnType($tableName, 'details'));
$this->assertEquals('decimal', Schema::getColumnType($tableName, 'amount'));
$this->assertEquals('integer', Schema::getColumnType($tableName, 'assigned_by'));
});
test('should has relation', function () {
$expectedRelations = [
"category",
"type",
"assignedBy",
];
$model = new Deposit;
foreach($expectedRelations as $relationName) {
$this->assertTrue(
method_exists($model, $relationName),
'No relation ' . $relationName. ' exists.',
);
}
});
test('should has category name', function () {
Deposit::factory()->create();
$model = Deposit::with('category')->first();
$this->assertArrayHasKey('name', $model->category);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment