Make CreateStudent action and test.

This commit is contained in:
Matt Young 2025-07-04 19:43:37 -05:00
parent 9717ae852e
commit 7379500e9a
2 changed files with 112 additions and 0 deletions

View File

@ -0,0 +1,39 @@
<?php
namespace App\Actions\Students;
use App\Exceptions\AuditionAdminException;
use App\Models\Student;
class CreateStudent
{
public function __construct()
{
}
public function __invoke(
string $firstName,
string $lastName,
int $grade,
array $optionalData = [],
int|string $school_id = 'user'
): Student {
if ($school_id === 'user') {
$school_id = auth()->user()->school_id;
}
if (Student::where('first_name', $firstName)->where('last_name', $lastName)
->where('school_id', $school_id)->exists()) {
throw new AuditionAdminException('Student already exists');
}
$newStudent = Student::create([
'first_name' => $firstName,
'last_name' => $lastName,
'grade' => $grade,
'school_id' => $school_id,
'optional_data' => $optionalData,
]);
return $newStudent;
}
}

View File

@ -0,0 +1,73 @@
<?php
/** @noinspection PhpUnhandledExceptionInspection */
use App\Actions\Students\CreateStudent;
use App\Exceptions\AuditionAdminException;
use App\Models\School;
use App\Models\Student;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->creator = app(CreateStudent::class);
});
it('can create a student with basic data', function () {
($this->creator)(
'John',
'Doe',
8,
[],
School::factory()->create()->id
);
expect(Student::first())->toBeInstanceOf(Student::class);
});
it('can include optional data', function () {
($this->creator)(
'John',
'Doe',
8,
['shirt_size' => 'M'],
School::factory()->create()->id
);
$student = Student::first();
expect($student->optional_data['shirt_size'])->toEqual('M');
});
it('uses the current users school if none is specified', function () {
$user = User::factory()->create();
$school = School::factory()->create();
$user->school_id = $school->id;
$user->save();
$this->actingAs($user);
($this->creator)(
'John',
'Doe',
8,
['shirt_size' => 'M'],
);
$student = Student::first();
expect($student->school_id)->toEqual($school->id);
});
it('throws an error if we try to create a duplicate student (same name and school)', function () {
$school = School::factory()->create();
($this->creator)(
'John',
'Doe',
8,
['shirt_size' => 'M'],
$school->id
);
($this->creator)(
'John',
'Doe',
11,
['shirt_size' => 'XL'],
$school->id
);
})->throws(AuditionAdminException::class, 'Student already exists');