Skip to content
Luca Ubiali Web Developer

Understanding Laravel's Context Capabilities - Testing with Context

September 10th, 2024
Continuous Learning

Episodes
https://laracasts.com/series/understanding-laravels-context-capabilities/episodes/4
https://laracasts.com/series/understanding-laravels-context-capabilities/episodes/5


The way Context is used within tests is pretty straightforward, it’s just another tool like Eloquent models or caching. Its data can be set or unset as needed to perform assertions. These couple lessons are handy to illustrate other methods available on the Context facade like has, when and forget.

Following is an updated version of the middleware created in the previous lesson. Context data active_account was always loaded from session. This might not always be the case, for example if Context already has some value in it, we want to ignore whatever is in session. has and when come in handy to implement this type of logic:

1namespace App\Http\Middleware;
2 
3 
4class AddContext
5{
6 /**
7 * Handle an incoming request.
8 *
9 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
10 */
11 public function handle(Request $request, Closure $next): Response
12 {
13 Context::when(
14 Context::has('active_account'),
15 fn($context) => null,
16 fn($context) => Context::add('active_account', session('active_account'))
17 );
18 
19 /*
20 * This is equivalent to the Context::when() above,
21 * maybe just a tad more readable
22 */
23 if(! Context::has('active_account')) {
24 Context::add('active_account', session('active_account'))
25 }
26 
27 Context::add([
28 'user' => Auth::user(),
29 ]);
30 
31 return $next($request);
32 }
33}

With the above changes in place, tests will look like the following. By adding or removing data from Context, we can control how the middleware will behave and test different if branches of the code.

1it('dashboard displays the account name using context', function() {
2 Context::add('active_account', $this->account);
3 
4 $this->get('/dashboard')
5 ->assertOk()
6 ->assertSee('Active Account Name');
7});
8 
9 
10it('dashboard displays the account name using session', function() {
11 Context::forget('active_account');
12 
13 $this->withSession(['active_account', $this->account]);
14 
15 $this->get('/dashboard')
16 ->assertOk()
17 ->assertSee('Active Account Name');
18});