Summer Sale! All accounts are 50% off this week.

Stolz's avatar

[5.1] Testing a form with an array of checkboxes fails

I want to test the "create" part of my users resource controller.

The associated view has a form with a text field named "name" and an array of checkboxes named "options[]".

My problem is I can't figure out how to populate the "options[]" field using the Laravel/Symfony crawler.

My controller method:

// route: user.create
public function create()
{
    dd(\Input::all());
}

My view:

<label for="name">Name</label>
<input name="name" type="text" value="" id="name" />

<label for="options1">
    <input id="options1" name="options[]" type="checkbox" value="1" />
    Option 1
</label>

<label for="options2">
    <input id="options2" name="options[]" type="checkbox" value="2" />
    Bar
</label>

<!-- ... and so on until option 10 ... -->

If I run this test

public function testCreateUser()
{
    $input = [
        'name' => 'Foo',
        'options => range(1, 10)
    ];

    $this->visit('user.create')
    ->submitForm('Create user', $input)
    ->seePageIs('user.show');
}

I get the error

1) UsersControllerTest::testCreateUser
InvalidArgumentException: Input "options[]" cannot take "1" as a value (possible values: 10).
./vendor/symfony/dom-crawler/Field/ChoiceFormField.php:144

So it seems the only valid value is 10. If I try with that value

public function testCreateUser()
{
    $input = [
        'name' => 'Foo',
        'options => 10
    ];

    $this->visit('user.create')
    ->submitForm('Create user', $input)
    ->seePageIs('user.show');
}

I get the error

1) UsersControllerTest::testCreateUser
InvalidArgumentException: Cannot set value on a compound field "options".
./vendor/symfony/dom-crawler/FormFieldRegistry.php:135

If I try again with

public function testCreateUser()
{
    $input = [
        'name' => 'Foo',
        'options => [10]
    ];

    $this->visit('user.create')
    ->submitForm('Create user', $input)
    ->seePageIs('user.show');
}

The submitForm() test is passed but the input received by the controller is

[
    "name" => "Foo",
    "options[0]" => "10"
]

Instead of the expected one

[
    "name" => "Foo",
    "options" => ["10"]
]

So my questions are...

why does symfony/dom-crawler/Field/ChoiceFormField only let me use the value 10 and not any others?

how can I build my test for my controller to receive the expected input?

0 likes
4 replies
jesseschutt's avatar

@Stolz - Thanks for posting this.

Were you ever able to get the testing working on the array of checkboxes? I'm still experiencing the issue where it will only accept the last value.

frans.brouwer's avatar

@jesseschutt

My solution was to index the compound field name for the checkboxes in order of appearance on the page

$inputs['compound_field_name[0]'] = 'Value 0';
$inputs['compound_field_name[1]'] = 'Value 1';
...
1 like

Please or to participate in this conversation.