Reputation: 2155
Based on the tutorial here: How to Dynamically Generate Forms Using Form Events
I have created a form that uses an event subscriber:
class PageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text');
$blockSubscriber = new AddBlocksSubscriber($builder->getFormFactory());
$builder->addEventSubscriber($blockSubscriber);
}
// ...
}
So far so good... until I decide to write some unit tests. ;) The use of the 'new' keyword is problematic because it prevents me from using a mock subscriber object.
I can think of two possible solutions:
Use test helpers/class posing, as described here: Seems a bit cumbersome though and requires a PHP extension. It doesn't 'feel' right having to do this, but might be a practical work-around.
Use dependency injection, e.g. make the PageType form constructor require an instance of a block subscriber.
The problem I'm finding here is that to create a subscriber object outside of the form, I'll also need an instance of the form builder. As the form is usually built by calling createForm()
in the controller, I won't usually have visibility of the builder from outside of the form.
Alternatively, is it really necessary to unit test forms, or is a functional test of the final output using the crawler sufficient?
For anyone who's implemented a few Symfony2 forms, I'd be interested to know how you approached it.
Upvotes: 1
Views: 2073
Reputation: 9464
The Symfony2 cookbook now contains a chapter dedicated to forms unit testing: http://symfony.com/doc/master/cookbook/form/unit_testing.html
Upvotes: 2