2016-08-01 64 views
2

我正在測試一個表單。在表單中,有一些複選框的名稱與有多個複選框可供選擇。PhpUnit測試,如何檢查複選框,如果在表單中有多個同名的複選框

所以我複選框這樣的:

<div class="col-sm-10"> 
    <div class="checkbox"> 
     <input id="department_1" name="departments[]" type="checkbox" value="1"> 
     <label for="department_1">Sales</label> 
    </div> 
              <div class="checkbox"> 
     <input id="department_2" name="departments[]" type="checkbox" value="2"> 
     <label for="department_2">Marketing</label> 
    </div> 
              <div class="checkbox"> 
     <input id="department_3" name="departments[]" type="checkbox" value="3"> 
     <label for="department_3">Tech Help</label> 
    </div> 
</div> 

我的測試代碼是這樣的:

public function testUserCreation() 
    { 
     $this->be(User::find(10)); 

     $this->visit('/users/create') 
      ->type('First', 'first_name') 
      ->type('Last', 'last_name') 
      ->type('[email protected]', 'email') 
      ->type('123456', 'password') 
      ->type('123456', 'password_confirmation') 
      ->check('departments') 
      ->press('Submit') 
      ->seePageIs('/users'); 
    } 

當我試圖檢查是否拋出錯誤:

InvalidArgumentException: Nothing matched the filter [permissions] CSS query provided for

回答

1

我管理這個的唯一方法是:

$this->visit('/users/create') 
    ->submitForm('Submit', [ 
     ... 
     ... 
     'departments[0]' => '1', 
     'departments[1]' => '2' 
    ]) 
    ->seePageIs('/users'); 

請注意,如果您想檢查第一個和最後一個項目,則必須遵循輸入的順序。

$this->visit('/users/create') 
     ->submitForm('Submit', [ 
      ... 
      ... 
      'departments[0]' => '1', 
      'departments[2]' => '3' // index 2 instead 1. 
     ]) 
     ->seePageIs('/users'); 
2

如果您在表單和測試中指定多個複選框的索引,那麼它就起作用。 形式:

<input id="department_1" name="departments[0]" type="checkbox" value="1"> 
<input id="department_2" name="departments[1]" type="checkbox" value="2"> 

單元測試:

public function testUserCreation() 
    { 
     $this->be(User::find(10)); 

     $this->visit('/users/create') 
      ->type('First', 'first_name') 
      ->type('Last', 'last_name') 
      ->type('[email protected]', 'email') 
      ->type('123456', 'password') 
      ->type('123456', 'password_confirmation') 
      ->check('departments[0]') 
      ->press('Submit') 
      ->seePageIs('/users'); 
    } 

使用命名索引工作爲好。

<input name="departments[department_1]" type="checkbox" value="1"> 
// [...] 
$this->check('departments[department_1]'); 
相關問題