[英]PHPUnit + Laravel 5.2 + Attribute not returning properly
User.php-漂亮的香草hasMany關系:
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相互配合的方式?
從模型外部(例如,在測試本身中):
$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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.