Skip to content

Instantly share code, notes, and snippets.

@jonathaningram
Created October 13, 2012 09:32
Show Gist options
  • Save jonathaningram/3883955 to your computer and use it in GitHub Desktop.
Save jonathaningram/3883955 to your computer and use it in GitHub Desktop.
Test that ensures that a controller action is only accessible by beta testers
<?php
namespace Acme\Bundle\WebBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\DiExtraBundle\Annotation as DI;
/**
* @Route("/feature-x")
*/
class FeatureXController
{
/**
* @Route("/{someSlug}/{anotherSlug}")
*
* @Template()
*/
public function featureXAction(Request $request, $someSlug, $anotherSlug)
{
if (!$this->getSecurityContext()->isGranted('FEATURE_BETA')) { // or, say, ROLE_BETA_TESTER depending on your needs
throw new NotFoundHttpException();
}
// do something for feature X
return array();
}
/**
* @DI\LookupMethod("router")
*
* @return RouterInterface
*/
protected function getRouter()
{
}
/**
* @DI\LookupMethod("security.context")
*
* @return SecurityContextInterface
*/
protected function getSecurityContext()
{
}
}
<?php
namespace Acme\Bundle\WebBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class FeatureXControllerTest extends WebTestCase
{
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testFeatureXThrowsNotFoundExceptionWhenUserIsNotBetaTester()
{
$securityContext = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
$securityContext
->expects($this->once())
->method('isGranted')
->will($this->returnValue(false))
;
$controller = $this->getMockBuilder('Acme\Bundle\WebBundle\Controller\FeatureXController')
->setMethods(array('getSecurityContext'))
->getMock();
$controller
->expects($this->once())
->method('getSecurityContext')
->will($this->returnValue($securityContext))
;
$request = $this->getMock('Symfony\Component\HttpFoundation\Request');
$controller->featureXAction($request, 'some-slug', 'another-slug');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment