Skip to content

Instantly share code, notes, and snippets.

@SimonEast
Last active March 11, 2021 15:07
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save SimonEast/b550e04300ac56cb5ac8eea704fccdfa to your computer and use it in GitHub Desktop.
Save SimonEast/b550e04300ac56cb5ac8eea704fccdfa to your computer and use it in GitHub Desktop.
Codeception - how to test for redirects
<?php
// Simply place the following two functions in _support/Helper/Acceptance.php
// Then you can call $I->verifyRedirect(...) inside your tests
namespace Helper;
class Acceptance extends \Codeception\Module
{
/**
* Ensure that a particular URL does NOT contain a 301/302
* nor a "Location" header
*/
public function verifyNoRedirect($url)
{
$phpBrowser = $this->getModule('PhpBrowser');
$guzzle = $phpBrowser->client;
// Disable the following of redirects
$guzzle->followRedirects(false);
$phpBrowser->_loadPage('GET', $url);
$response = $guzzle->getInternalResponse();
$responseCode = $response->getStatus();
$locationHeader = $response->getHeader('Location');
$this->assertNotEquals($responseCode, 301);
$this->assertNotEquals($responseCode, 302);
$this->assertNull($locationHeader);
$guzzle->followRedirects(true);
}
/**
* Ensure that a particular URL redirects to another URL
*
* @param string $startUrl
* @param string $endUrl (should match "Location" header exactly)
* @param integer $redirectCode (301 = permanent, 302 = temporary)
*/
public function verifyRedirect($startUrl, $endUrl, $redirectCode = 301)
{
$phpBrowser = $this->getModule('PhpBrowser');
$guzzle = $phpBrowser->client;
// Disable the following of redirects
$guzzle->followRedirects(false);
$phpBrowser->_loadPage('GET', $startUrl);
$response = $guzzle->getInternalResponse();
$responseCode = $response->getStatus();
$locationHeader = $response->getHeader('Location');
$this->assertEquals($responseCode, $redirectCode);
$this->assertEquals($endUrl, $locationHeader);
$guzzle->followRedirects(true);
}
}
@FelikZ
Copy link

FelikZ commented Sep 21, 2017

Thanks!

@Syednazirhussain
Copy link

nice staff

@Vitexus
Copy link

Vitexus commented Dec 17, 2017

Star for you!
Thanks

@zacharylinke
Copy link

Very helpful, thanks!!

@skiingdomo
Copy link

$response->getStatus(); was throwing an error, changed to $response->getStatusCode(); and it seems to work.

Thanks mate.

@thedava
Copy link

thedava commented Mar 11, 2021

Thanks a lot!

One small thing:
The parameters are swapped in line 53:

$this->assertEquals($responseCode, $redirectCode);

should be

$this->assertEquals($redirectCode, $responseCode);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment