2015-06-21 25 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 –