1

I'm trying to test a form but i got unreachable field exception.

My controller's code :

class StudentController extends Controller
{
  /**
   * @Route("/student/new",name="create_new_student")
   */
   public function newAction(Request $request){
      $student = new Student();
      $form = $this->createFormBuilder($student)->add('name',TextType::class)
          ->add('save',SubmitType::class,['label' => 'Create student'])->getForm();
      $form->handleRequest($request);
      if($form->isSubmitted()){
           $student = $form->getData();
           $name = $student->getName();
           echo "Your name is ".$name;
           die();       
      }

      return $this->render(':Student:new.html.twig',['form' => $form->createView()]);
   }
}

My StudentControllerTest :

class StudentControllerTest extends WebTestCase
{

  public function testNew(){
    $client = static::createClient();
    $crawler = $client->request('POST','/student/new');
    $form = $crawler->selectButton('Create student')->form();
    $form['name'] = 'Student1';
    $crawler = $client->submit($form);
    $this->assertGreaterThan(0,$crawler->filter('html:contains("Your name is Student1")')->count());
  }
}

When i run the test using phpunit i got :

InvalidArgumentException: Unreachable field "name"

I'm following the tutorial from https://symfony.com/doc/current/testing.html

2 Answers 2

5

You should use the $form['form_name[subject]'] syntax

public function testNew(){

      $client = static::createClient();

      //you should request it with GET method, it's more close to the reality
      $crawler = $client->request('GET','/student/new');

      $form = $crawler->selectButton('Create student')->form();

      $form['form_name[name]'] = 'Student1';

      // [...]
  }
Sign up to request clarification or add additional context in comments.

Comments

1

Try this way. Edit Test

$form = $crawler->selectButton('Create student')->form(['name' => 'Student1']);

Edit Controller:

...

$name = $student->getName();

return new Response("Your name is ". $name);

Do not kill what Symfony request.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.