Search code examples
phpsymfonyphpunitfunctional-testing

How to test update action?


I am trying to test my updateAction which allows to update my users in database but I don't know how I can test it... I have succed to test my createAction which add an user in my database. So I would like to get the user id which I have just created to udpdate this.

This is my function testCreate :

public function testCreate()
    {
        $crawler = $this->client->request('GET', '/admin/user/new');

        $buttonCrawlerNode = $crawler->selectButton('submit');

        $form = $buttonCrawlerNode->form(array(
            'myapp_usertype[email]'            => '[email protected]',
            'myapp_usertype[role]'             => 'ROLE_USER',
            'myapp_usertype[password][first]'  => 'test',
            'myapp_usertype[password][second]' => 'test',
        ));

        $this->client->submit($form);
    }

Solution

  • Not so dry, but you can try:

    public function testUpdate()
    {
        $user = static::$kernel->getContainer()->get('doctrine')->getRepository('YourUserBundle:User')->findOneByEmail('[email protected]');
    
        $crawler = $client->request('GET', '/admin/user/edit/'.$user->getId());
        $form = $crawler->selectButton('submit')->form();
    
        $form = $buttonCrawlerNode->form(array(
            'myapp_usertype[email]'            => '[email protected]',
            'myapp_usertype[role]'             => 'ROLE_ANOTHER',
            'myapp_usertype[password][first]'  => 'test',
            'myapp_usertype[password][second]' => 'test',
            ));
    
            $crawler = $client->submit($form);
    
        $user = static::$kernel->getContainer()->get('doctrine')->getRepository('YourUserBundle:User')->find($user->getId());
    
        $this->assertEquals(
            '[email protected]',
            $user->getEmail()
        );
    
        $this->assertEquals(
            'ROLE_ANOTHER',
            $user->getRole()
        );
    }