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()
复制/粘贴断言:
$user->transactions->count()
=> 1
此外,当我在本地手动执行这些步骤时 - 它可以正常工作。因此,Laravel 5.2似乎正如预期的那样发挥作用。但是,PHPUnit不是。
我想知道是否有可能我错过了Laravel 5.2和PHPUnit相互协作的方式?
答案 0 :(得分:0)
从模型外部(例如在测试中):
$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