2012-05-20 13 views
6

Mam app, który używa subdomen do trasy do agencji:Jak przetestować subdomen na podstawie tras w Symfony2

foo.domain.dev -> Agency:showAction(foo) 
bar.domain.dev -> Agency:showAction(bar) 
domain.dev  -> Agency:indexAction() 

Każdy z tych odpowiadają jednostki Agencji i kontrolera.

Mam słuchacza, który nasłuchuje zdarzenia onDomainParse i zapisuje subdomenę w atrybutach żądania.

/** 
* Listens for on domainParse event 
* Writes to request attributes 
*/ 
class SubdomainListener { 
    public function onDomainParse(Event $event) 
    { 
     $request = $event->getRequest(); 
     $session = $request->getSession(); 
     // Split the host name into tokens 
     $tokens = $this->tokenizeHost($request->getHost()); 

     if (isset($tokens['subdomain'])){ 
      $request->attributes->set('_subdomain',$tokens['subdomain']); 
     } 

    } 
    //... 
} 

I wtedy to wykorzystać w sterowniku do przekierowania do akcji show:

class AgencyController extends Controller 
{ 

    /** 
    * Lists all Agency entities. 
    * 
    */ 
    public function indexAction() 
    { 
     // We reroute to show action here. 
     $subdomain = $this->getRequest() 
         ->attributes 
         ->get('_subdomain'); 
     if ($subdomain) 
      return $this->showAction($subdomain); 


     $em = $this->getDoctrine()->getEntityManager(); 

     $agencies = $em->getRepository('NordRvisnCoreBundle:Agency')->findAll(); 

     return $this->render('NordRvisnCoreBundle:Agency:index.html.twig', array(
      'agencies' => $agencies 
     )); 
    } 
    // ... 

} 

Moje pytanie brzmi:

Jak mogę fałszywe to robiąc test z WebTestCase?

Odpowiedz

7

Odwiedź subdomeny nadrzędnymi nagłówki HTTP dla żądania i testu na prawej stronie:

Nietestowane, mogą zawierać błędy

class AgencyControllerTest extends WebTestCase 
{ 
    public function testShowFoo() 
    { 
     $client = static::createClient(); 

     $crawler = $client->request('GET', '/', array(), array(), array(
      'HTTP_HOST'  => 'foo.domain.dev', 
      'HTTP_USER_AGENT' => 'Symfony/2.0', 
     )); 

     $this->assertGreaterThan(0, $crawler->filter('html:contains("Text of foo domain")')->count()); 
    } 
} 
+0

Ach to było również w [docs] (http://symfony.com/doc/current/book/testing.html#testing-configuration). Dzięki – max

7

podstawie docs Symfony na trasach opartych na hostach, Testing your Controllers:

$crawler = $client->request(
    'GET', 
    '/', 
    array(), 
    array(), 
    array('HTTP_HOST' => 'foo.domain.dev') 
); 

Jeśli nie chcesz pad wszystkie żądania z parametrów tablicowych, t Jego może być lepiej:

$client->setServerParameter('HTTP_HOST', 'foo.domain.dev'); 
$crawler = $client->request('GET', '/'); 

... 

$crawler2 = $client->request('GET', /foo'); // still sends the HTTP_HOST 

Jest też setServerParameters() metoda na kliencie, jeśli masz kilka parametrów do zmiany.

Powiązane problemy