2014-01-31 41 views
6

我想在用戶提交沒有任何數據的表單時使用PHPUnit測試我的Symfony2應用程序。Symfony2測試:使用html過濾:包含返回一個值

我的驗證已激活,因此錯誤消息在導航器中正確顯示。例如,在實體:

class Foo 
{ 

    /** 
    * @var string 
    * 
    * @Assert\NotBlank() 
    * @ORM\Column(name="name", type="string", length=255) 
    */ 
    private $name; 

    /** 
    * @var string 
    * 
    * @Assert\NotBlank() 
    * @ORM\Column(name="city", type="string", length=255) 
    */ 
    private $city; 

} 

而這個實體的類型:

class FooType extends AbstractType 
{ 
    /** 
    * @param FormBuilderInterface $builder 
    * @param array $options 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('name', 'text') 
      ->add('city', 'text'); 
    } 

    // ... 
} 

當我提交表單,沒有任何數據,響應包含2個消息「該值應不爲空」。

所以在我的測試中,我想取出這個2級的消息,但過濾函數只是返回1:

public function testShouldNotSaveANewFooWhenDataIsEmpty() 
{ 
    $crawler = $this->client->request('GET', '/foo/new'); 
    $form = $crawler->selectButton('Add')->form(array(
     'foo[name]' => '', 
     'foo[city]' => '' 
    )); 

    $crawler = $this->client->submit($form); 
    echo $crawler->filter('html:contains("This value should not be blank")')->count(); // Should display 2, not 1 
} 

你有什麼想法嗎?

+0

也許是因爲'foo [name]'和'bureau [city]'不填充這兩個字段? –

+0

糟糕,我的複製/粘貼出錯。修正了我的問題,謝謝。 – ncrocfer

回答

6

的選擇您使用的手段html:contains("This value should not be blank")獲得包含"This value should not be blank"<html>標籤。即使此字符串出現兩次,每頁也只有一個<html>標記,因此您永遠不會計算2個過濾的項目。

的解決方案是使用更具體的規則:

$crawler->filter('div:contains("This value should not be blank")') 

使用其中包含你的錯誤消息的標記名稱。默認情況下,它是<div>,但您可能已在您的Twig模板中對此進行了更改。

+0

太好了,謝謝你的解釋! – ncrocfer