表单测试:如何将表单提交到现有表单?

时间:2015-09-23 12:57:35

标签: symfony phpunit functional-testing domcrawler

我使用两种方法来测试我的表单:

使用$form = …->form();

然后设置$form数组的值(更确切地说这是\Symfony\Component\DomCrawler\Form对象):

documentation的完整示例:

$form = $crawler->selectButton('submit')->form();

// set some values
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';

// submit the form
$crawler = $client->submit($form);

直接发送POST数据:

以前的代码不适用于forms which manage collections(依赖于Javascript创建的字段),因为如果该字段不存在则会引发错误。这就是为什么我也使用this other way

documentation的完整示例:

// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));

这个解决方案是我知道测试使用Javascript添加的字段管理集合的表单的唯一方法(请参阅上面的文档链接)。但是第二种解决方案更难使用,因为:

  • 它不会检查哪些字段存在,当我必须提交一个包含现有字段and的表单时,这是不切实际的,该集合依赖于使用Javascript动态创建的字段
  • 需要手动添加表单_token

我的问题

是否可以使用第一种方式的语法来定义现有字段,然后使用第二种语法添加新动态创建的字段?

换句话说,我想有这样的事情:

$form = $crawler->selectButton('submit')->form();

// set some values for the existing fields
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';

// submit the form with additional data
$crawler = $client->submit($form, array('name' => 'Fabien'));

但是我收到了这个错误:

  

无法访问的字段“名称”

并且$form->get('name')->setData('Fabien');会触发相同的错误。

此示例并不完美,因为表单没有集合,但它足以向您显示我的问题。

当我向现有表单添加一些字段时,我正在寻找一种避免此验证的方法。

1 个答案:

答案 0 :(得分:0)

这可以通过从submit()方法调用稍微修改过的代码来完成:

// Get the form.
$form = $crawler->filter('button')->form();

// Merge existing values with new values.
$values = array_merge_recursive(
    $form->getPhpValues(),
    array(
        // New values.
        'FORM_NAME' => array(
            'COLLECTION_NAME' => array(
                array(
                    'FIELD_NAME_1' => 'a',
                    'FIELD_NAME_2' => '1',
                )
            )
        )
    )
);

// Submit the form with the existing and new values.
$crawler = $this->client->request($form->getMethod(), $form->getUri(), $values,
    $form->getPhpFiles());

此示例中包含新闻值的数组对应于您拥有包含这些name的字段的表单:

<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_1]" />
<input type="…" name="FORM_NAME[COLLECTION_NAME][A_NUMBER][FIELD_NAME_2]" />

字段的数量(索引)无关紧要,PHP将合并数组并提交数据,Symfony将在相应的字段中转换此数据。

相关问题