2014-01-17 25 views
0

我正在爲僅包含兩個字段的簡單模型編寫一些單元測試:question_id和title。在非可填寫字段上工作的批量指派

我給自己定的模型可填寫陣列只包括標題:

protected $fillable = array('title'); 

我也創建了以下的單元測試:

/** 
    * @expectedException Illuminate\Database\Eloquent\MassAssignmentException 
    */ 
    public function testAnswerQuestionIdCanNotBeMassAssigned() 
    { 
     $params = ['question_id' => 1, 'title' => 'something']; 
     $answer = new Answer($params); 
    } 

但是,不會引發任何異常,導致測試失敗。

我在這裏錯過了什麼嗎?

任何意見讚賞。

謝謝。

回答

2

你可以看到爲什麼在模型

public function fill(array $attributes) 
{ 
    $totallyGuarded = $this->totallyGuarded(); 

    foreach ($this->fillableFromArray($attributes) as $key => $value) 
    { 
     $key = $this->removeTableFromKey($key); 

     // The developers may choose to place some attributes in the "fillable" 
     // array, which means only those attributes may be set through mass 
     // assignment to the model, and all others will just be ignored. 
     if ($this->isFillable($key)) 
     { 
      $this->setAttribute($key, $value); 
     } 
     elseif ($totallyGuarded) 
     { 
      throw new MassAssignmentException($key); <--- only if totally guarded 
     } 
    } 

    return $this; 
} 
填充方法