2016-02-28 41 views
2

user.php的 - 相當香草的hasMany關係:的PHPUnit + Laravel 5.2 +屬性不返回正確

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並切換到叮叮):

$ php artisan tinker 

搶用戶(驗證爲創建相同的用戶從測試):

$user = App\User::first() 

複製/粘貼斷言:

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

此外,當我手動經過的步驟當地 - 它的工作原理。所以,看起來Laravel 5.2是按預期行事的。但是,PHPUnit不是。

我想知道是否有可能我錯過Laravel 5.2和PHPUnit一起工作的方式?

+1

如果在最後一個斷言之前放置** $ user = $ user-> fresh(); **,會發生什麼?我懷疑該事務可能不會同步,除非獲取新實例。 – macghriogair

+0

謝謝@macghriogair讓我走下正確的道路。多謝。如果你想獲得信用,我會非常樂意把它給你 - 只要發表一個類似於我寫的答案 - 擴大你的評論。再次感謝 - 救生員。 –

+0

沒關係,快樂我可以幫助:) – macghriogair

回答

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

相關問題