I actually found a better solution that fixes all the problems with the sessions. I will first explain the problem and then provide my solution.
The problem arises due to the fact that the session driver used for tests is the Array driver, and this driver uses a NullSessionHandler. Because of this the session data is not saved between requests. The code that creates the array session driver is follows:
// Illuminate/Session/SessionManager.php
/**
* Create an instance of the "array" session driver.
*
* @return \Illuminate\Session\Store
*/
protected function createArrayDriver()
{
return new Store($this->app['config']['session.cookie'], new NullSessionHandler);
}
So my thought was to change the driver used in the testing environment to the native driver, but this didn't work. I found this strange, and after some testing I found out that setting the session driver option was always overridden to the array driver. The code that does this is in the SessionServiceProvider file:
// Illuminate/Session/SessionServiceProvider.php
/**
* Setup the default session driver for the application.
*
* @return void
*/
protected function setupDefaultDriver()
{
if ($this->app->runningInConsole())
{
$this->app['config']['session.driver'] = 'array';
}
}
Because tests are run through the console, the session driver will always be set to array, even if you specify something else in the config file for the testing environment.
So my solution is to create a TestingServiceProvider myself, that sets the correct session driver:
// App/Providers/TestingServiceProvider.php
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class TestingServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
if ($this->app->environment() == 'testing')
{
$this->app['config']['session.driver'] = 'native';
}
}
}
Do make sure you register this service provider after the SessionServiceProvider in config/app.php, because otherwise the change will be overridden again.
This will work nicely until some other fix will be implemented.