The issue you're encountering with the test failing due to the session missing the expected key [errors] is likely because the validation errors are not being properly triggered or handled in your controller. To ensure that validation errors are correctly returned, you need to validate the request data before proceeding with the update logic.
Here's a step-by-step solution to address the problem:
-
Add Validation to the Controller:
Ensure that the
activefield is validated before any other logic is executed in theupdatemethod of your controller.
use Illuminate\Validation\Rule;
public function update(Request $request, Character $character)
{
// Validate the request data
$request->validate([
'active' => ['required', Rule::in([0, 1])],
]);
// if the character is already the active
if ($character->active) {
// then redirect to the characters index
return redirect('characters');
}
// get the player's active character if any
$activecharacter = Character::where('user_id', auth()->user()->id)
->where('active', 1)
->first(['id', 'active']);
// if the player has an active character
if ($activecharacter) {
// mark the previous character as not active
$activecharacter->update(['active' => 0]);
}
// set the selected character as the active one
$character->update(['active' => 1]);
// then redirect to the characters index
return response(200);
}
-
Update the Test:
Ensure that the test is correctly structured to handle the validation errors. The
assertInvalidmethod should be used to check for validation errors.
it('requires valid data', function ($active) {
// Arrange
Belt::factory()->create([
'min_xp' => 0,
]);
$character = Character::factory()->create();
$this->actingAs($character->user)
->put(route('characters.update', ['character' => $character]), ['active' => $active])
->assertSessionHasErrors('active');
})->with([
[null],
[true],
[1.5],
['!!!!'],
[' '],
[str_repeat('a', 16)],
[str_repeat('a', 2)],
]);
- Ensure Proper Error Handling in the Frontend: Make sure that your frontend is prepared to handle validation errors if they occur. This might involve displaying error messages to the user.
By adding validation to your controller and ensuring your test is correctly checking for validation errors, you should be able to resolve the issue with the session missing the expected key [errors].