Synfony

Page 125

The createClient() method returns a client, which is like a browser that you'll use to crawl your site: Listing 10-7

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

The request() method (see more about the request method) returns a Crawler3 object which can be used to select elements in the Response, click on links, and submit forms. The Crawler only works when the response is an XML or an HTML document. To get the raw content response, call $client->getResponse()->getContent().

Click on a link by first selecting it with the Crawler using either an XPath expression or a CSS selector, then use the Client to click on it. For example, the following code finds all links with the text Greet, then selects the second one, and ultimately clicks on it: Listing 10-8

1 $link = $crawler->filter('a:contains("Greet")')->eq(1)->link(); 2 3 $crawler = $client->click($link);

Submitting a form is very similar; select a form button, optionally override some form values, and submit the corresponding form: Listing 10-9

1 2 3 4 5 6 7 8

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

// set some values $form['name'] = 'Lucas'; $form['form_name[subject]'] = 'Hey there!'; // submit the form $crawler = $client->submit($form);

The form can also handle uploads and contains methods to fill in different types of form fields (e.g. select() and tick()). For details, see the Forms section below.

Now that you can easily navigate through an application, use assertions to test that it actually does what you expect it to. Use the Crawler to make assertions on the DOM: Listing 10-10

1 // Assert that the response matches a given CSS selector. 2 $this->assertGreaterThan(0, $crawler->filter('h1')->count());

Or, test against the Response content directly if you just want to assert that the content contains some text, or if the Response is not an XML/HTML document: Listing 10-11

1 $this->assertRegExp( 2 '/Hello Fabien/', 3 $client->getResponse()->getContent() 4 );

3. http://api.symfony.com/2.2/Symfony/Component/DomCrawler/Crawler.html

PDF brought to you by generated on March 18, 2013

Chapter 10: Testing | 125


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.