4

Liip Functional Test Bundleを使用して、Symfony で機能テストを作成しています。

現在、フォームの送信に行き詰まっています。
機能テストを使用して新しい「ログ」を追加しようとしています。

UI を使用して新しいログを追加しようとすると、次の要求パラメーターが取得されます。

'WorkLog' => array(
    'submit' => '',
    'hours' => '8',
    'minutes' => '0',
    'note' => 'some text',
    '_token' => '4l5oPcdCRzxDKKlJt_RG-B1342X52o0C187ZLLVWre4' 
);

しかし、テストがフォームを送信すると、トークンなしで同じパラメーターを取得します

 'WorkLog' => array(
    'submit' => '',
    'hours' => '8',
    'minutes' => '0',
    'note' => 'some text'
);

「_token」フィールドをフォームリクエストに追加することで問題を解決できると思っていましたが、実行してから再度テストすると、エラーが発生しました。

InvalidArgumentException: 到達不能フィールド "_token"

機能テストのコード:

namespace App\AdminBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;

use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\BrowserKit\Cookie;

class LogControllerTest extends WebTestCase
{
    private $client;
    private $em;
    private $fixtures;

    public function setUp()
    {
        $this->client = static::makeClient();
        $this->em = $this->client->getContainer()->get('doctrine')->getManager();

        $this->fixtures = $this->loadFixtures(array(
            'App\AdminBundle\DataFixtures\ORM\LoadUserData',
            'App\AdminBundle\DataFixtures\ORM\LoadSubscriptionTypesData',
            'App\AdminBundle\DataFixtures\ORM\LoadSubscriptionData',
            'App\AdminBundle\DataFixtures\ORM\LoadWorkLogData',
        ))->getReferenceRepository();
    }

    public function testAddNewLog()
    {
        $accountId = $this->fixtures->getReference('userAccount')->getId();

        // log in with admin account
        $this->logIn('adminAccount');

        $crawler = $this->client->request('GET', '/admin/worklog/account/'.$accountId.'/add');
        $csrfToken = $this->client->getContainer()->get('form.csrf_provider')->generateCsrfToken('post_type');

        $form = $crawler->selectButton('WorkLog_submit')->form(array(
            'WorkLog' => array(
                'hours' => '8',
                'minutes' => '0',
                'note' => 'some text',
                '_token' => $csrfToken
            ),
        ), 'POST');

        $crawler = $this->client->submit($form);
    }
}

私の質問:トークンを使用してフォームを送信するにはどうすればよいですか?

4

2 に答える 2