Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flush and reset Eloquent model events when testing.
<?php
class TestCase extends Illuminate\Foundation\Testing\TestCase {
/**
* Creates the appliation.
*
* @return \Symfony\Component\HttpKernel\HttpKernelInterface
*/
public function createApplication()
{
$unitTesting = true;
$testEnvironment = 'testing';
return require __DIR__.'/../../bootstrap/start.php';
}
public function setUp()
{
parent::setUp();
$this->resetEvents();
}
/**
* Flush and reboot Eloquent model events.
*
* @return void
*/
public function resetEvents()
{
foreach ($this->getModels() as $model)
{
call_user_func([$model, 'flushEventListeners']);
call_user_func([$model, 'boot']);
}
}
/**
* Get the model names from their filename.
*
* @return array
*/
protected function getModels()
{
$files = File::files(base_path() . '/app/models');
foreach ($files as $file)
{
$models[] = pathinfo($file, PATHINFO_FILENAME);
}
return $models;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.