Laravel 4模型事件不适用于PHPUnit

Ale*_*ski 7 phpunit laravel laravel-4

我使用creating模型事件在Laravel 4中构建模型侧验证:

class User extends Eloquent {

    public function isValid()
    {
        return Validator::make($this->toArray(), array('name' => 'required'))->passes();
    }

    public static function boot()
    {
        parent::boot();

        static::creating(function($user)
        {
            echo "Hello";
            if (!$user->isValid()) return false;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

它运作良好,但我有PHPUnit的问题.以下两个测试完全相同,但是第一个测试通过:

class UserTest extends TestCase {

    public function testSaveUserWithoutName()
    {
        $count = User::all()->count();

        $user = new User;
        $saving = $user->save();

        assertFalse($saving);                       // pass
        assertEquals($count, User::all()->count()); // pass
    }

    public function testSaveUserWithoutNameBis()
    {
        $count = User::all()->count();

        $user = new User;
        $saving = $user->save();

        assertFalse($saving);                       // fail
        assertEquals($count, User::all()->count()); // fail, the user is created
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试在同一个测试中创建一个用户两次,它就可以工作,但就像绑定事件只出现在我的测试类的第一个测试中一样.所述echo "Hello";第一测试执行过程中仅打印一次.

我简化了我的问题,但你可以看到问题:我不能在不同的单元测试中测试几个验证规则.我从几个小时开始尝试几乎所有东西,但我现在快要跳出窗户!任何的想法 ?

Lau*_*nce 3

这个问题在 Github 中有详细记录。请参阅上面的评论,进一步解释它。

我修改了 Github 中的“解决方案”之一,以在测试期间自动重置所有模型事件。将以下内容添加到您的 TestCase.php 文件中。

应用程序/测试/TestCase.php

public function setUp()
{
    parent::setUp();
    $this->resetEvents();
}


private function resetEvents()
{
    // Get all models in the Model directory
    $pathToModels = '/app/models';   // <- Change this to your model directory
    $files = File::files($pathToModels);

    // Remove the directory name and the .php from the filename
    $files = str_replace($pathToModels.'/', '', $files);
    $files = str_replace('.php', '', $files);

    // Remove "BaseModel" as we dont want to boot that moodel
    if(($key = array_search('BaseModel', $files)) !== false) {
        unset($files[$key]);
    }

    // Reset each model event listeners.
    foreach ($files as $model) {

        // Flush any existing listeners.
        call_user_func(array($model, 'flushEventListeners'));

        // Reregister them.
        call_user_func(array($model, 'boot'));
    }
}
Run Code Online (Sandbox Code Playgroud)