Skip to content

Instantly share code, notes, and snippets.

@roni-estein
Created November 19, 2018 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roni-estein/24ef04b2821a16aa373677d512d76895 to your computer and use it in GitHub Desktop.
Save roni-estein/24ef04b2821a16aa373677d512d76895 to your computer and use it in GitHub Desktop.
<?php
namespace Tests;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
// Use this area to add macros that are relevant to the database
// It will have access to testcase and domain test case. But
// try and isolate logic and macros to the proper layer to
// make it easier to find logic and move it from project
// to project.
abstract class DBTestCase extends DomainTestCase
{
use RefreshDatabase;
public function setUp()
{
parent::setUp();
DB::statement('PRAGMA foreign_keys=on');
// Created refresh to remove deleted models from a collection once it's
// refreshed to ensure collection size change
EloquentCollection::macro('refresh', function ($with = []) {
if ($this->isEmpty()) {
return new static;
}
$model = $this->first();
$freshModels = $model->newQueryWithoutScopes()
->with(is_string($with) ? func_get_args() : $with)
->whereIn($model->getKeyName(), $this->modelKeys())
->get()
->getDictionary();
return $freshModels;
});
}
/**
* @param $expected
* @param $actual
* @return bool
*
* Returns a comparison with the fresh expected, to remove unwanted
* metadata like was recently created flag producing false negatives
*/
public function assertSameAttributes($expected, $actual): void
{
$this->assertEquals($expected->fresh(), $actual);
}
/**
* Make a simple assertion that the object exists in the database
*
* @param $object
* @return DBTestCase
*/
public function assertDatabaseHasObject($object)
{
return $this->assertDatabaseHas($object->getTable(), ['id' => $object->id]);
}
/**
* Make a simple assertion that the object does not exist in the database
*
* @param $object
* @return DBTestCase
*/
public function assertDatabaseMissingObject($object)
{
return $this->assertDatabaseMissing($object->getTable(), ['id' => $object->id]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment