mardi 25 février 2020

Why $form->isValid() returns false when testing although it's true in production?

I'm using Symfony 3.4 and I'm writing tests for my actions

And as mentioned in the title $form->isValid() returns false although it works fine when I test the form in production.

In my tests I try to simulate POST request like so:

$crawler = $this->_client->request('GET', $this->_router->generate('product_new'));
$form = $crawler->filter('form')->form();
$values = $form->getPhpValues();
$values['product']['code'] = 'PRD';
$values['product']['name'] = 'TEST PRODUCT';
$values['product']['price'] = 550;
$this->_client->request($form->getMethod(), $form->getUri(), $values, $form->getPhpFiles());
$response = $this->_client->getResponse();
// the response should return 302 because I'm doing redirection after submitting the form
// so this one should return true
$this->assertEquals(Response::HTTP_FOUND, $response->getStatusCode());

And this is the action in ProductController class:

/**
 * @Route("/new", name="product_new")
 * @Method({"GET", "POST"})
 */
public function createAction(){
      $product = new Product();
      $form = $this->createForm(ProductType::class, $product);

      $form->handleRequest($request);
      // when I remove $form->isValid() the test works fine
      if ($form->isSubmitted() && $form->isValid()) {
          $em = $this->getDoctrine()->getManager();
          $em->persist($product);
          $em->flush();
          return $this->redirectToRoute('product_show', array('code' => $product->getCode()));
      }

      return $this->render('@Commerce/product/new.html.twig', array(
        'product' => $product,
        'form' => $form->createView()
      )); 
}

What am I missing here ?

Aucun commentaire:

Enregistrer un commentaire