public
Last active

Functional Testing in Yii using Goutte

  • Download Gist
SiteTest.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
<?php
 
use Goutte\Client;
 
class SiteTest extends CTestCase {
protected $client;
 
public function setUp() {
parent::setUp();
$this->client = new Client();
}
 
public function open($route, $params=array()) {
$url = explode('phpunit', Yii::app()->createUrl($route, $params));
return TEST_BASE_URL.$url[1];
}
 
public function testIndex() {
$crawler = $this->client->request('GET', $this->open('site/index'));
$this->assertEquals('My Web Application', $crawler->filter('title')->text());
}
 
public function testContact() {
$crawler = $this->client->request('GET', $this->open('site/contact'));
$this->assertEquals('My Web Application - Contact Us', $crawler->filter('title')->text());
 
$form = $crawler->filter('input[type=submit]')->form();
$this->assertEquals('POST', strtoupper($form->getMethod()));
$this->assertTrue($form->has('ContactForm[name]'));
 
// set some values
$form['ContactForm[name]'] = 'tester';
$form['ContactForm[email]'] = 'tester@example.com';
$form['ContactForm[subject]'] = 'test subject';
 
// submit the form
$crawler = $this->client->submit($form);
$this->assertEquals('Body cannot be blank.', $crawler->filter('#ContactForm_body_em_')->text());
}
 
public function testLoginLogout() {
$crawler = $this->client->request('GET', $this->open('site/index'));
 
// ensure the user is logged out
$this->assertNotRegExp('/Logout/', $this->client->getResponse()->getContent());
 
// test login process, including validation
$crawler = $this->client->click($crawler->selectLink('Login')->link());
$form = $crawler->filter('input[type=submit]')->form();
$this->assertTrue($form->has('LoginForm[username]'));
 
$crawler = $this->client->submit($form);
$this->assertRegExp('/Username cannot be blank./', $this->client->getResponse()->getContent());
$this->assertRegExp('/Password cannot be blank./', $this->client->getResponse()->getContent());
 
$form['LoginForm[username]'] = 'demo';
$form['LoginForm[password]'] = 'demo';
$crawler = $this->client->submit($form);
$this->assertNotRegExp('/Password cannot be blank./', $this->client->getResponse()->getContent());
$this->assertRegExp('/Logout/', $this->client->getResponse()->getContent());
 
// test logout process
$this->assertNotRegExp('/Login/', $this->client->getResponse()->getContent());
$crawler = $this->client->click($crawler->selectLink('Logout (demo)')->link());
$this->assertRegExp('/Login/', $this->client->getResponse()->getContent());
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.