2014-12-02 89 views
2

我有两个字段的表单。提交后,将显示该表单的相同控制器的重定向。symfony 2中的测试表单phpunit

的方法如下:

public function chartsAction($path, Request $request) 
{ 
    // display form 

    if(isset($_POST)) 
    { 
     // handle form submission 
    } 
} 

当它不是一个POST请求,则URL为charts/

当它是一个POST请求时,该URL是例如charts/dateFrom/2013-08/dateTo/2014-02,所以这是方法的$ path参数,并且两个变量取决于表单。


现在我想测试这个。问题是表单重定向给了我相同的图表/网站。它只是不会为路由添加$ path参数。这是怎么回事?我的测试方法:

public function testChartsAction() 
    { 
     $crawler = $this->client->request('GET', '/charts', [], [], $this->credintials); 

     $form = $crawler->selectButton('dateChooser[Choose]')->form([ 
      'dateChooser[dateFrom]' => '2014-08', 
      'dateChooser[dateTo]' => '2014-12', 
     ]); 
     $this->client->submit($form); 
     $crawler = $this->client->followRedirect(); 

     $this->assertTrue($this->client->getResponse()->isRedirect('/charts/dateFrom/2014-08/dateTo/2014-12')); 
     $this->assertTrue($this->client->getResponse()->isSuccessful()); 
    } 

第一个断言让我错误。

+0

尝试测试isRedirect的followRedirect方法之前 – Matteo 2014-12-02 21:27:57

+0

它仍然给我/图表重定向从形式,没有GET参数。 – khernik 2014-12-02 21:31:57

回答

2

我想你应该跳过“isRedirect”断言。在表单处理程序,您可以设置一个成功的提示信息,将在响应页面呈现:

$client = $this->makeClient(true); 
$client->followRedirects(); 
$crawler = $client->request('GET', $url); 

$form = $crawler->filter('#formID')->form(); 
$form->setValues(array(
    "formsample[firstname]" => "test firstname", 
    "formsample[lastname]" => "test lastname" 
)); 

$client->setServerParameter("HTTP_X-Requested-With" , "XMLHttpRequest"); 
$client->submit($form); 
$response = $client->getResponse(); 
$this->assertContains('Your data has been saved!', $response->getContent());