Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use crawler in controller

// src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php
namespace Acme\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DemoControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/demo/hello/Fabien');

        $this->assertGreaterThan(0, $crawler->filter('html:contains("Hello Fabien")')->count());
    }
}

this working OK in my tests, but i would like use this crawler also in controller. How can i do it?

i make route, and add to controller:

<?php

// src/Ens/JobeetBundle/Controller/CategoryController

namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\DemoBundle\Entity\Category;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class CategoryController extends Controller
{   
  public function testAction()
  {
    $client = WebTestCase::createClient();

    $crawler = $client->request('GET', '/category/index');
  }

}

but this return me error:

Fatal error: Class 'PHPUnit_Framework_TestCase' not found in /acme/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php on line 24
like image 422
Patrick Groozder Avatar asked Sep 05 '12 13:09

Patrick Groozder


2 Answers

The WebTestCase class is a special class that is designed to be run within a test framework (PHPUnit) and you cannot use it in your controller.

But you can create a HTTPKernel client like this:

use Symfony\Component\HttpKernel\Client;

...

public function testAction()
{
    $client = new Client($this->get('kernel'));
    $crawler = $client->request('GET', '/category/index');
}

Note that you will only be able to use this client to browse your own symfony application. If you want to browse an external server you will need to use another client like goutte.

The crawler created here is the same crawler returned by WebTestCase so you can follow the same examples detailed in the symfony testing documentation

If you need more information, here is the documentation for the crawler component and here is the class reference

like image 110
Carlos Granados Avatar answered Oct 16 '22 18:10

Carlos Granados


You shouldn't use WebTestCase in prod environment, because WebTestCase::createClient() creates test client.

In your controller you should do something like this (I recommend you to use Buzz\Browser):

use Symfony\Component\DomCrawler\Crawler;
use Buzz\Browser;

...
$browser = new Browser();
$crawler = new Crawler();

$response = $browser->get('/category/index');
$content = $response->getContent();
$crawler->addContent($content);
like image 37
Vitalii Zurian Avatar answered Oct 16 '22 18:10

Vitalii Zurian