Skip to content

Instantly share code, notes, and snippets.

@dwightwatson
Created September 9, 2014 02:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwightwatson/a645e7f5f6c8c52445d8 to your computer and use it in GitHub Desktop.
Save dwightwatson/a645e7f5f6c8c52445d8 to your computer and use it in GitHub Desktop.
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