Don't make a static call and inject the class. That makes it easy to mock
Nov 10, 2022
16
Level 54
Testing Endpoint and not calling action class
I'm trying to test when an administrator tries to suspend a user that the SuspendAction is run and is redirected. I would instead test specifics of the action class in a separate test however I'm not sure how I can prevent it from getting inside of the actual action class.
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Users;
use App\Actions\Users\SuspendAction;
use App\Exceptions\CannotBeSuspendedException;
use App\Http\Controllers\Controller;
use App\Models\User;
class SuspendController extends Controller
{
/**
* Suspend a user.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\RedirectResponse
*/
public function __invoke(User $user)
{
$this->authorize('suspend', $user);
try {
SuspendAction::run($user);
} catch (CannotBeSuspendedException $e) {
return redirect()->back()->with('error', $e->getMessage());
}
return to_route('users.index');
}
}
beforeEach(function () {
$this->user = User::factory()->create();
});
test('invoke calls suspend action and redirects', function () {
$this->actingAs(administrator())
->patch(action([SuspendController::class], $this->user))
->assertRedirect(action([UsersController::class, 'index']));
RetireAction::shouldRun()->with($this->user);
});
Please or to participate in this conversation.