Hey, I´m currently working on a feature where users can view all their sessions across multiple devices. To feature test this functionality I´m doing the following:
- Create the sessions table migration
php artisan session:table
<server name="SESSION_DRIVER" value="database"/>
SESSION_DRIVER=database
<h1>Sessions</h1>
{{ $sessions }}
@auth
<form action="logout" method="post">
@csrf
<button type="submit">Logout</button>
</form>
@endauth
@guest
<form action="login" method="post">
@csrf
<button type="submit">Login</button>
</form>
@endguest
<?php
use App\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
$sessions = auth()->check()
? DB::table('sessions')->whereUserId(auth()->user()->id)->get()
: collect([]);
return view('welcome', [
'sessions' => $sessions,
]);
});
Route::post('login', function () {
auth()->login(User::first());
return back();
});
Route::post('logout', function () {
auth()->logout();
return back();
});
Note: For testing purposes I´ve created a dummy user in the DatabaseTableSeeder and ran php artisan migrate --seed
<?php
namespace Tests\Feature;
use App\User;
use Tests\TestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function setUp(): void
{
parent::setUp();
$this->user = factory(User::class)->create();
}
/** @test */
function passes()
{
$this->actingAs($this->user);
$this->get('/');
$this->get('/')
->assertViewHas('sessions', DB::table('sessions')->whereUserId($this->user->id)->get());
}
/** @test */
function fails()
{
$this->actingAs($this->user)
->get('/')
->assertViewHas('sessions', DB::table('sessions')->whereUserId($this->user->id)->get());
}
}
Now my problem is that my tests are not green, but in reality everything works as expected. I´ve created an example repo so you can check out my code: https://github.com/stebrl/database-sessions-test
Would be really nice if someone could help!