Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Unit Testing Forms with constraints

I've got a form which isn't connected to a entity but does have constraints like mentioned in here: http://symfony.com/doc/current/book/forms.html#adding-validation

ContactBundle\Tests\Form\Type\TestedTypeTest::testSubmitValidData Symfony\Component\OptionsResolver\Exception\InvalidOptionsException: The option "constraints" does not exist. Known options are: "action", "attr", "auto_initialize", "block_name", "by_reference", "compound", "data", "data_class", "disabled", "empty_data", "error_bubbling", "inherit_data", "label", "label_attr", "mapped", "max_length", "method", "pattern", "post_max_size_message", "property_path", "read_only", "required", "translation_domain", "trim", "virtual"

Here is part of the form:

class ContactType extends AbstractType
{

/**
 * Build the form
 * @param \Symfony\Component\Form\FormBuilderInterface $builder BuilderInterface
 * @param array $aOption Array of options
 */
public function buildForm(FormBuilderInterface $builder, array $aOption)
{
    ///..
    $builder->add('name', 'text', array(
                'constraints' => array(
                    new NotBlank(),
                    new Length(array('min' => 3)),
                ),
            ))
            ->add('address', 'textarea', array(
                'required' => false
            ))
            //..
            ;
    //..

Here is the unit test

class TestedTypeTest extends TypeTestCase
{

public function testSubmitValidData()
{
    $formData = array(
        'name' => 'Test Name',
        'address' => '',
    );
    $type = new ContactType();
    $form = $this->factory->create($type, $formData);
    $form->submit($formData);

    $this->assertTrue($form->isSynchronized());

    $view = $form->createView();
    $children = $view->children;

    foreach (array_keys($formData) as $key) {
        $this->assertArrayHasKey($key, $children);
    }
}
}

I'm guessing that this is a problem with the test instead of the form as the form works as expected. I'm not sure what I should change. Any help or advice would be handy

Thanks

like image 227
pfwd Avatar asked Nov 19 '14 16:11

pfwd


1 Answers

I think the problem is that you also pass the formData to the factory's create method.

It should be fine to just pass the form data via $form->submit($formData) like you already have in your code

More docs: http://symfony.com/doc/current/cookbook/form/unit_testing.html

EDIT:

Well it seems you have to add the validator/constaint extensions to the factory object in your test setup like stated here http://symfony.com/doc/current/cookbook/form/unit_testing.html#adding-custom-extensions

like image 100
Rob Avatar answered Nov 14 '22 23:11

Rob