I'm writing some tests with the codeception REST module.
The project I'm working on is in the early stages and we haven't implemented token-based authentication yet; so for now the authentication is done via a REST API but it uses $_SESSION
for persistence.
To test authenticated requests I need to keep the PHPSESSID
cookie and send it with every request. Is there a way to read/set cookies when working with the REST module?
Ok I got the solution. My suite name is api
, so codeception generated a file at tests/_support/Helper/Api.php
. Before making changes here, I had to edit my suite YAML file api.suite.yml
to enable the helper. My YAML file looks like this:
class_name: ApiTester
modules:
enabled:
- REST:
depends: PhpBrowser
url: https://website.com/api/
part: Json
- \Helper\Api
Now that the file is enabled, run codecept build
so that it updates the generated files to read your helper.
In the Api
helper class, I added two methods:
public function capturePHPSESSID()
{
$cookie = $this->getClient()->getCookieJar()->get('PHPSESSID');
echo "Cookie: ", $cookie;
}
/**
* @return \Symfony\Component\HttpKernel\Client|\Symfony\Component\BrowserKit\Client $client
*/
protected function getClient()
{
return $this->getModule('REST')->client;
}
This is all that you need to read the PHPSESSID cookie! Feel free to capture it so you can then write a method to re-use it by setting calling $this->getClient()->getCookieJar()->set(....)