Skip to content

Instantly share code, notes, and snippets.

@supercoffee
Created February 24, 2017 05:41
Show Gist options
  • Save supercoffee/b4790861050c252c3ed9d7f8840179d4 to your computer and use it in GitHub Desktop.
Save supercoffee/b4790861050c252c3ed9d7f8840179d4 to your computer and use it in GitHub Desktop.
Reset the booted flag of Laravel models between Tests.

Laravel testing issues

During a Codeception test using the Laravel module, the application is loaded every time refreshing the dynamic components of the system. But certain static fields aren't reset between test runs, so it breaks the system.

Specifically, a new instance of Dispatcher is set on Eloquent models, but the Model's booted flags are not reset.
After the first test run, no models in the system will have listeners attached.

So to solve this issue, I made a custom test hook that resets the model booted flags after each test run.

Installation

Paste ModelResetExtension.php into your _support directory (located in your test directory.

Then add an entry in codeception.yml to enable this extension.

extensions:
    enabled:
        - ModelResetExtension
<?php
use Codeception\Extension;
use Illuminate\Database\Eloquent\Model;
class ModelResetExtension extends Extension
{
public static $events = [
'test.after' => 'resetModelBootFlags'
];
public function resetModelBootFlags()
{
$modelClass = new ReflectionClass(Model::class);
$booted = $modelClass->getProperty('booted');
$booted->setAccessible(true);
$booted->setValue([]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment