2015-06-21 20 views
0

我有密碼突變運行測試:Laravel 5.1無法對用戶密碼的Mutator

/** 
* Mutator for setting the encryption on the user password. 
* 
* @param $password 
*/ 
public function getPasswordAttribute($password) 
{ 
    $this->attributes[ 'password' ] = bcrypt($password); 
} 

那我想測試:

/** 
* A basic check of password mutator. 
* 
* @return void 
*/ 
public function testCheckPasswordEncryptionUserAttribute() 
{ 
    $userFactory = factory('Project\User')->create([ 
     'password' => 'test' 
    ]); 

    $user = User::first(); 

    $this->assertEquals(bcrypt('test'), $user->password); 
} 

,當測試運行我得到這個錯誤:

1) UserTest::testCheckPasswordEncryptionUserAttribute 
Failed asserting that null matches expected '$2y$10$iS278efxpv3Pi6rfu4/1eOoVkn4EYN1mFF98scSf2m2WUhrH2kVW6'. 

測試失敗後,我嘗試dd()密碼屬性,但也失敗了。我的第一個想法是這可能是一個大規模分配問題(剛剛閱讀了這個問題),但密碼在$ fillable(這是有道理的,它會在那裏),然後我注意到隱藏在User類中的$,閱讀文檔中的相關內容,並刪除$ hidden的密碼索引,但當您嘗試訪問密碼屬性時仍會產生空值。

你會如何測試這個增變器,或者我錯過了什麼?

回答

2

您只需在方法名稱中將「get」更改爲「set」即可。

以「get」開頭的方法是訪問器。這些不應該改變字段/屬性值,但返回一個「變異」值(你的返回沒有什麼,這就是爲什麼你得到null)。

以「set」開頭的方法旨在改變字段的值(mutators),這看起來正是你所需要的。

http://laravel.com/docs/5.0/eloquent#accessors-and-mutators

/** 
* Mutator for setting the encryption on the user password. 
* 
* @param $password 
*/ 
public function setPasswordAttribute($password) 
{ 
    $this->attributes['password'] = bcrypt($password); 
} 

您可以隱藏的 「密碼」,因爲這會不會影響你的測試。

P.S.如果我沒有錯,factory('...')->create()返回一個新創建的模型(\Illuminate\Database\Eloquent\Model)的一個實例,因此您不必做User::first()

/** 
* A basic check of password mutator. 
* 
* @return void 
*/ 
public function testCheckPasswordEncryptionUserAttribute() 
{ 
    $user = factory('Project\User')->create(['password' => 'test']); 

    $this->assertTrue(Hash::check('test', $user->password)); 
} 
+0

嗨,這是有道理不使密碼可填寫的,但我想知道爲什麼他們將它設置爲可以在乾淨的安裝上進行填充你只是使用查詢生成器來更新密碼,然後如果你不能使用創建大規模分配它。測試現在運行,但由於值不匹配而失敗,我不明白這是如何發生的,因爲我正在設置密碼,並且現在mutator正在使用您的修復程序正常工作,但絕對不會有同樣的值。 – mtpultz

+0

嗨,我改變了這個使用password_hash和password_verify,現在比較哈希正確,並通過phpunit。感謝您的幫助 – mtpultz

+0

不客氣。不知道爲什麼它可以由deafult填寫。你確定?它可以隱藏,但不太可能被填充。 我認爲你有比較密碼的問題,因爲即使你散列相同的值,bcrypt也會產生不同的結果。 您也可以使用Laravel的哈希門面來擦除密碼(請參閱編輯器中的測試代碼): http://laravel.com/docs/5.0/hashing –