PHPUnit + Laravel 5.2 + 属性未正确返回

PHPUnit + Laravel 5.2 + Attribute not returning properly

User.php - 漂亮的香草有很多关系:

public function transactions()
{
    return $this->hasMany('App\Transaction');
}

UserTest.php:

public function testTransactionsAttribute()
{
    $user = Auth::user();

    // Verify logged in user is expected user.
    $this->assertTrue($user->username == 'something');

    // Pay something.
    $transaction = $user->payMembershipFee();

    // Verify transaction is in database
    $this->seeInDatabase('transactions', ['amount' => 50, 'user_id' => $user->id]);

    // Verify transaction belongsTo relationship
    $this->assertTrue($transaction->user->username == 'something');

    // Verify user hasMany relationship - fails
    $this->assertTrue($user->transactions->count() > 0, 'The user should have at least one transaction associated.');
}

这里是有趣的地方(我没有修改数据库表 - 只是离开 PHPUnit 并切换到 Tinker):

$ php artisan tinker

抓取用户(已验证是从测试创建的同一用户):

$user = App\User::first()

Copy/Paste断言:

$user->transactions->count()
=> 1

此外,当我在本地手动执行这些步骤时 - 它有效。因此,Laravel 5.2 似乎按预期运行。但是,PHPUnit 不是。

我想知道我是否可能在 Laravel 5.2 和 PHPUnit 相互协作的过程中遗漏了什么?

从模型外部(例如在测试本身):

$user = $user->fresh();

在模型内部不能做类似的事情:

$this = $this->fresh();

因此,在为用户创建交易的方法中:

public function createTransaction()
{
    $transaction = new Transaction;
    ...
    $transaction->save();

    // Refresh the relationship specifically        
    $this->load('transactions');

    // There is also fresh([])
    // which is supposed to be able to accept multiple relationships

    return $transaction;
}

https://laracasts.com/discuss/channels/testing/refresh-a-model