adminUser = User::factory()->admin()->create(); $this->schools = School::factory()->count(5)->create(); }); it('only shows for an admin user', function () { // Act & Assert $checkRoute = 'admin.students.create'; get(route($checkRoute))->assertRedirect(route('home')); actingAs($this->adminUser); get(route($checkRoute))->assertOk(); actingAs(User::factory()->create()); get(route($checkRoute))->assertRedirect(route('dashboard')); }); it('submits a post request', function () { // Arrange actingAs($this->adminUser); // Act & Assert $response = get(route('admin.students.create')); $response->assertOk(); $response->assertSeeInOrder([ 'form', 'method', 'POST', 'action=', route('admin.students.store'), '/form', ]); }); it('has all needed fields', function () { // Arrange actingAs($this->adminUser); $fieldNames = [ 'first_name', 'last_name', ]; // Act & Assert $response = get(route('admin.students.create')); $response->assertOk(); foreach ($fieldNames as $fieldName) { $response->assertSeeInOrder([ 'input', 'name=', $fieldName, '/', ]); } $response->assertSeeInOrder([ 'select', 'name=', 'school_id', '/select', ]); $response->assertSeeInOrder([ 'select', 'name=', 'grade', '/select', ]); }); it('has all schools in a dropdown', function () { // Arrange actingAs($this->adminUser); // Act & Assert $response = get(route('admin.students.create')); $response->assertOk(); foreach ($this->schools as $school) { $response->assertSeeInOrder([ 'option', 'value=', $school->id, $school->name, '/option', ]); } }); it('rejects a submission by a non administrator', function () { // Arrange actingAs(User::factory()->create()); // Act & Assert $response = post(route('admin.students.store'), [ 'first_name' => 'New First Name', 'last_name' => 'New Last Name', ]); $response->assertRedirect(route('dashboard')); }); it('allows an administrator to create a student', function () { // Arrange $newSchool = School::factory()->create(['name' => 'New School']); actingAs($this->adminUser); $newData = [ 'first_name' => 'New First Name', 'last_name' => 'New Last Name', 'grade' => '9', 'school_id' => $newSchool->id, ]; // Act $response = post(route('admin.students.store'), $newData); /** @noinspection PhpUnhandledExceptionInspection */ $response ->assertSessionHasNoErrors() ->assertRedirect(route('admin.students.index')); // Get the latest created user $createdStudent = Student::where('first_name', $newData['first_name'])->first(); expect($createdStudent->first_name)->toBe($newData['first_name']) ->and($createdStudent->last_name)->toBe($newData['last_name']) ->and($createdStudent->grade)->toEqual($newData['grade']) ->and($createdStudent->school->name)->toBe($newSchool->name); get(route('admin.students.index')) ->assertOk() ->assertSee($newData['first_name']) ->assertSee($newData['last_name']) ->assertSee($newData['grade']) ->assertSee($newSchool->name); });