Skip to content

Instantly share code, notes, and snippets.

@JoshuaDoshua
Created April 5, 2021 04:53
Show Gist options
  • Save JoshuaDoshua/698af012e80aaca97f497307925a084b to your computer and use it in GitHub Desktop.
Save JoshuaDoshua/698af012e80aaca97f497307925a084b to your computer and use it in GitHub Desktop.
assertDatabaseHasModel Laravel Unit Assertion
<?php
...
/**
* Format date values for asserting database model existence
*
* @param string $table
* @param Model $model
* @param ?string $connection
* @return bool
*/
protected function assertDatabaseHasModel(string $table, Model $model, ?string $connection = null)
{
$attributes = $model->attributesToArray();
// dates
$dates = $model->getDates();
collect(array_keys($attributes))
->filter(function(string $key) use ($dates) {
return in_array($key, $dates);
})->each(function($field) use ($model, &$attributes) {
$attributes[$field] = $model->$field->toDateTimeString();
});
// force accessing protected fields
$reflect = new \ReflectionClass($model);
// casts
$castsProp = $reflect->getProperty('casts');
$castsProp->setAccessible(true);
$casts = $castsProp->getValue($model);
collect(array_keys($attributes))
->filter(function(string $key) use ($casts) {
return array_key_exists($key, $casts);
})->each(function($field) use ($casts, $model, &$attributes) {
switch ($casts[$field]):
case "boolean":
$attributes[$field] = (string) intval($attributes[$field]);
break;
default:
return;
endswitch;
});
// appended attributes won't show in database
$appendsProp = $reflect->getProperty('appends');
$appendsProp->setAccessible(true);
$appends = $appendsProp->getValue($model);
if (!empty($appends)):
foreach ($appends as $attribute)
unset($attributes[$attribute]);
endif; // has appends
// relations
// $relations = $model->getRelations();
// $relationsProp = $reflect->getProperty('relations');
// $relationsProp->setAccessible(true);
// $relations = $relationsProp->getValue($model);
// if ($relations)
// dd($relations);
// collect(array_keys($attributes))
// ->filter(function(string $key) {
// return Str::endsWith($key, '_id');
// })->each(function($field) use ($model, &$attributes) {
// $attributes[$field] = strval($model->$field);
// });
$this->assertDatabaseHas($table, $attributes, $connection);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment