Created
October 4, 2012 16:38
-
-
Save JoshuaEstes/3834831 to your computer and use it in GitHub Desktop.
Create a symfony test client that is authenticated
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This method goes in your class, does not check for errors and assumes everything is fine | |
*/ | |
protected static function createAuthenticatedClient(array $options = array(), array $server = array()) | |
{ | |
$client = static::createClient($options, $server); | |
$client->request('GET', '/login'); | |
$form = $client->getCrawler()->selectButton('Login')->form(); | |
$client->submit($form, array( | |
'_username' => 'admin', | |
'_password' => 'admin', | |
)); | |
return $client; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\BlogBundle\Tests\Controller; | |
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; | |
class DefaultControllerTest extends WebTestCase | |
{ | |
public function testIndex() | |
{ | |
$client = $this->createAuthenticatedClient(); | |
} | |
private function createAuthenticatedClient() | |
{ | |
$client = static::createClient(); | |
$client->request('GET', '/'); | |
// Make sure we are redirected to the login page | |
$this->assertEquals(302, $client->getResponse()->getStatusCode()); | |
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/login')); | |
$client->followRedirect(); | |
// submit login form | |
$form = $client->getCrawler()->selectButton('Login')->form(); | |
$client->submit($form, array( | |
'_username' => 'admin', | |
'_password' => 'admin', | |
)); | |
// Login is successful | |
$this->assertEquals(302, $client->getResponse()->getStatusCode()); | |
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/')); | |
$client->followRedirect(); | |
// On the homepage | |
$this->assertEquals(200, $client->getResponse()->getStatusCode()); | |
return $client; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment