【问题标题】:Error trying to select a form from symfony2 crawler?尝试从 symfony2 爬虫中选择表单时出错?
【发布时间】:2013-07-11 16:52:52
【问题描述】:

我不断收到以下错误:

There was 1 error:

1) Caremonk\MainSiteBundle\Tests\Controller\SecurityControllerFunctionalTest::testIndex
InvalidArgumentException: The current node list is empty.

但是当我导航到 localhost/login 时,我的表单会填充正确的内容。这句话说...

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

导致错误。我的测试出了什么问题?

功能测试:

<?php

namespace Caremonk\MainSiteBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SecurityControllerFunctionalTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/login');

        $form = $crawler->selectButton('login')->form();
        $form['username'] = 'testActive';
        $form['password'] = 'passwordActive';
    }
}

树枝视图:

{# src/Acme/SecurityBundle/Resources/views/Security/login.html.twig #}
{% if error %}
    <div>{{ error.message }}</div>
{% endif %}

<form action="{{ path('caremonk_mainsite_login_check') }}" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="_username" value="{{ last_username }}" />

    <label for="password">Password:</label>
    <input type="password" id="password" name="_password" />

    {#
        If you want to control the URL the user is redirected to on success (more details below)
        <input type="hidden" name="_target_path" value="/account" />
    #}

    <button type="submit">login</button>
</form>

【问题讨论】:

    标签: php unit-testing testing symfony phpunit


    【解决方案1】:

    Vineet 的答案是正确的,但是...在我看来,从按钮中获取形式并不是一个好主意。 更好的尝试:

    $crawler->filter('form[name=yourAwesomeFormName]')->form();
    

    或更改类名称、id 等。在一个视图上可以有超过 1 个具有相同提交值的表单

    【讨论】:

    • 非常感谢,想知道除了按钮之外是否还有其他方法可以获取表单!
    • 绝对是最好的选择,因为文本可能会改变并且不会反映在开发端(取决于翻译,客户请求更改的措辞......)
    • 我同意,通过标签选择表单感觉不确定并且可能很容易损坏。这里的一个提示是使用一个可以在所有测试中使用的表单 id 的常量。如果它改变了,你只需要改变常量。
    【解决方案2】:

    开始在 symfony2 中进行功能测试,发现您的问题没有得到解答,所以我们开始吧,

    selectButton 方法将实际的按钮文本作为字符串参数。因此,如果您的按钮是“请提交我的表单”,那将是您的文本。

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

    查看 Andrew Stackoverflow的答案

    【讨论】:

    • 参数也需要在前面加上下划线,例如_username
    【解决方案3】:

    好的,这就是我遇到此错误的原因以及解决方法。

    (使用Goutte) 爬虫就像一个带有 GET 的浏览器。

    所以,在做的时候:

    $client = new Client();
    $crawler = $client->request('GET', '/login');
    

    爬虫正在尝试访问http://localhost/login

    所以,基本上,我把它改成了:

    $client = new Client();
    $crawler = $client->request('GET', 'http://site.dev/app_dev.php/login');
    

    site.dev 是我的 symfony 项目的虚拟主机。

    希望对你有帮助!

    【讨论】:

      【解决方案4】:

      selectButton() 通过namealt 图像值选择按钮。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多