【发布时间】:2013-09-11 22:51:00
【问题描述】:
我正在尝试模拟 Ardent 包在做什么。这是在保存之前验证模型。
我创建了这本书BaseModel(根据Laravel Testing decoded 书)。并添加了这段代码:
class BaseModel extends Eloquent {
protected static $rules = [];
public $errors = [];
public function validate(){
$v = Validator::make($this->attributes, static::$rules);
if($v->passes()) {
return true;
}
$this->errors = $v->messages();
return false;
}
public static function boot(){
parent::boot();
static::saving(function($model){
if($model->validate() === true){
foreach ($model->attributes as $key => $value) {
if(preg_match("/[a-zA-Z]+_confirmation/", $key)){
array_splice($model->attributes, array_search($key, array_keys($model->attributes)), 1);
}
}
echo "test"; //This is for debugging if this event is fired or not
return true;
} else {
return false;
}
});
}
}
现在,这是我的Post 模型:
class Post extends BaseModel {
public static $rules = array(
'body' => 'required',
'user_id' => 'required',
);
}
在这个测试中,我预计它会失败。相反,它通过了! , $post->save() 返回真!
class PostTest extends TestCase {
public function testSavingPost(){
$post = new Post();
$this->assertFalse($post->save());
}
}
当我尝试在 saving 事件中抛出 echo 语句时。它没有出现,所以我知道我定义的saving 事件没有被调用。我不知道为什么。
【问题讨论】:
标签: php unit-testing laravel eloquent