40

Using the Symfony2 WebTestCase, I have the following test :

$client->request('GET', '/');
$this->assertTrue($client->getResponse() instanceof RedirectResponse);

$crawler = $client->followRedirect();

I would like to test the new url, after the redirection ends with /login but I have found no way to access the new URL.

5 Answers 5

36

You can get the current URL with $client->getResponse()->headers->get('location'), and assert it ends with /login using assertRegExp().

$this->assertRegExp('/\/login$/', $client->getResponse()->headers->get('location'));
1
  • Works for Symfony 2.8.
    – Moonchild
    Commented Jun 18, 2016 at 9:08
26

Just tried Samy Dindane solution without success (maybe something changed from 2.0)

Anyway, in 2.1, I was able to retrieve current URL in test with:

$client->getRequest()->getUri()

Then, you can use assertRegexp().

1
  • 2
    Not true in symfony 2.3 Commented Jul 16, 2013 at 11:19
14

You can also do something like this (Symfony 2.3)

$client->getHistory()->current()->getUri()
0
10

You can add this row $client->getResponse()->getTargetUrl() before $client->followRedirect() to get the url where you will be redirected

1
  • 2
    Without a doubt my preferred answer if you want the URL without following the redirect. Note that in order to make this validate in your IDE, you can do the following (taken from my unit test, thus the assertions): $this->assertTrue($client->getResponse()->isRedirect()); /** @var RedirectResponse $response */ $response = $client->getResponse(); $this->assertEquals($new_url, $response->getTargetUrl()); Commented Mar 2, 2017 at 8:33
2

Test redirect from /sample to /target (can be absolute url as well)

$crawler = $client->request('GET', '/sample');

$this->assertTrue($client->getResponse() instanceof RedirectResponse);
$this->assertTrue($client->getResponse()->isRedirect('/target'));
1
  • Working on Symfony 5.0. You can have this assertion isRedirect and then follow that redirect with: $client->followRedirect();
    – sergio
    Commented Sep 30, 2020 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.