Skip to content

Instantly share code, notes, and snippets.

@JoshuaEstes
Created October 4, 2012 16:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JoshuaEstes/3834831 to your computer and use it in GitHub Desktop.
Save JoshuaEstes/3834831 to your computer and use it in GitHub Desktop.
Create a symfony test client that is authenticated
<?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;
}
<?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