При функциональном тестировании регистрации пользователя: когда csrf_protection: true
, регистрация не удалась, даже если регистрация прошла успешно в dev. Тест csrf_protection: false
успешно, когда csrf_protection: false
. (Приложение использует PUGXMultiUserBundle). Я попытался очистить кэш теста и т.д. $this->client->getResponse()->getContent()
в файл показывает регистрационную форму со всеми полями, но пароль завершен. _token
отладки теста показывает, что поле _token
отправлено, но, похоже, вышло из fos_user_registration_form[]
прежде чем перейти к public function request($method, $uri, array $parameters = array(), array $files = array(), array $server = array(), $content = null, $changeHistory = true)
линии public function request($method, $uri, array $parameters = array(), array $files = array(), array $server = array(), $content = null, $changeHistory = true)
в Client.php
.
На данный момент я установил csrf_protection: false
в config_test.yml
- не лучшее решение!
namespace Truckee\UserBundle\Tests\Controller;
use Liip\FunctionalTestBundle\Test\WebTestCase;
class RegistrationFunctionalTest extends WebTestCase
{
private $volunteerValues;
private $client;
public function setup()
{
$classes = array(
'Truckee\MatchingBundle\DataFixtures\SampleData\LoadFocusSkillData',
'Truckee\MatchingBundle\DataFixtures\SampleData\LoadTemplateData',
);
$this->loadFixtures($classes);
$this->client = static::createClient();
$this->volunteerValues = array(
'fos_user_registration_form' => array(
'email' => '[email protected]',
'username' => 'hvolunteer',
'firstName' => 'Harry',
'lastName' => 'Volunteer',
'plainPassword' => array(
'first' => '123Abcd',
'second' => '123Abcd',
),
'focuses' => array('1'),
'skills' => array('14'),
)
);
}
public function submitVolunteerForm()
{
$crawler = $this->client->request('GET', '/register/volunteer');
$form = $crawler->selectButton('Save')->form();
$this->client->request($form->getMethod(), $form->getUri(), $this->volunteerValues);
}
public function testRegisterVolunteer()
{
$this->submitVolunteerForm();
$this->client->enableProfiler();
if ($profile = $this->client->getProfile()) {
$mailCollector = $this->client->getProfile()->getCollector('swiftmailer');
$this->assertEquals(1, $mailCollector->getMessageCount());
}
$crawler = $this->client->followRedirect();
$this->assertTrue($crawler->filter('html:contains("An email has been sent")')->count() > 0);
}
...
}
_token
<div class="row">
<div class="col-md-5">
{%if form._token is defined %}{{ form_widget(form._token) }}{% endif %}
{{ form_row(form.firstName) }}
{{ form_row(form.lastName) }}
</div>
</div>
После долгих экспериментов я обнаружил свое собственное решение: добавьте 'intention' => 'registration',
в класс формы пользователя! Doh!
Основная проблема заключалась в использовании метода массива ($this->client->request($form->getMethod(), $form->getUri(), $this->volunteerValues);
отправки формы. токен csrf! Вместо этого я сделал это, чтобы разрешить использование поля токена формы:
public function submitVolunteerForm()
{
$crawler = $this->client->request('GET', '/register/volunteer');
$form = $crawler->selectButton('Save')->form();
$form['fos_user_registration_form[email]'] = '[email protected]';
$form['fos_user_registration_form[username]'] = 'hvolunteer';
$form['fos_user_registration_form[firstName]'] = 'Harry';
$form['fos_user_registration_form[lastName]'] = 'Volunteer';
$form['fos_user_registration_form[plainPassword][first]'] = '123Abcd';
$form['fos_user_registration_form[plainPassword][second]'] = '123Abcd';
$form['fos_user_registration_form[focuses]'] = [1];
$form['fos_user_registration_form[skills]'] = [14];
$crawler = $this->client->submit($form);
}