【问题标题】:Form tests: How to submit a collection to an existing form? [duplicate]表单测试:如何将集合提交到现有表单? [复制]
【发布时间】:2015-12-20 19:29:24
【问题描述】:

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

通过使用$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'); 会触发同样的错误。

这个例子并不完美,因为表单没有集合,但足以说明我的问题。

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

【问题讨论】:

  • 我认为这会帮助你解决这个问题...stackoverflow.com/questions/15454760/…
  • @NandaKumar 谢谢,但它与我的问题中的语法相同(通过直接发送POST 数据: 部分)。
  • 你能把你渲染的html表单贴出来吗?
  • @NandaKumar:我想为不存在的字段提交值,您确定它会帮助您查看表单吗?
  • 在代码中设置节点之前,您需要将动态元素添加到节点中...请查看此链接以获取参考api.symfony.com/2.4/Symfony/Component/DomCrawler/Crawler.html

标签: symfony phpunit functional-testing domcrawler


【解决方案1】:

这可以通过从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());

本例中包含新闻值的数组对应于一个表单,其中您有一个包含这些names 的字段:

<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会在相应的字段中转换这些数据。

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2014-06-28
    • 2020-12-04
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多