我刚开始使用 TDD,我正在尝试在模型中测试验证。目前,我所有的测试都通过了,但我认为它们不应该通过。 testBodyIsRequiredToValidate() 应该会失败,因为我没有将它添加到规则数组中。当我从规则数组中删除所需的标题时,我的所有测试都按预期失败了。但是,添加所需的标题会导致它们全部通过。
我的测试:
class PostTest extends TestCase {
public function testTitleIsRequiredToValidate()
{
$post = new Post;
$post->body = 'foobar';
$this->assertFalse($post->validate(compact('post')));
}
public function testBodyIsRequiredToValidate()
{
$post = new Post;
$post->title = 'foobar';
$this->assertFalse($post->validate(compact('post')));
}
}
我的模型:
class Post extends Eloquent {
public function validate($input)
{
$rules = array(
'title' => 'required'
);
$v = Validator::make($input, $rules);
if ($v->passes()) {
return true;
} else {
return false;
}
}
}
最佳答案
发生这种情况是因为您的验证有误。您将模型本身传递给验证器,但您应该传递一个关联数组。
- 当您从规则中删除
title
时,您传递了一个空规则,因此验证将始终为真,这就是所有测试失败的原因。 - 当您将
title
添加到规则中时,验证将始终为假,因此您的所有测试都会通过,因为验证器的第一个参数没有名为title
的数组元素>.
纠正此问题的一种方法是将您的验证行更改为:
$v = Validator::make(array('title' => $input['post']->title), $rules);
在这里,您从$input
数组中获取了$post
,因为compact()
将把它放入一个以变量名为键的数组中。然后您访问对象的 title
属性并将其设为 title
键的值,以便验证器能够找到并验证它。
我不得不提一下,您的验证技术对我来说有点不好。您将数组中的对象传递给同一对象的函数。为什么不在函数中获取对象呢?
我会这样写验证器函数:
public function validate() {
$rules = array(
'title' => 'required'
);
$v = Validator::make($this->toArray(), $rules);
return $v->passes();
}
所以我可以在测试中调用这样的函数:
$this->assertFalse($post->validate());
关于unit-testing - 使用 Laravel 测试模型验证时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173147/