In the next couple of lessons, we'll add automated tests to ensure that our app works as expected. This first test will be to check if only the admin user can access some parts of the application.
To write tests, for the data we will use Factories.
For this test, first, we will add a factory callback to the UserFactory
called admin
. This way when we will create a user which needs to be an admin we will be able to chain the admin()
method to the factory call.
database/factories/UserFactory.php:
class UserFactory extends Factory{ // ... public function admin(): static { return $this->afterCreating(fn (User $user) => $user->update(['is_admin' => true])); }}
Now we can create a feature test.
php artisan make:test AdminRoutesTest
tests/Feature/AdminRoutesTest.php:
class AdminRoutesTest extends TestCase{ use RefreshDatabase; public function testAdminCanAndOthersCannotAccessQuestionsPage() { $admin = User::factory()->admin()->create(); $response = $this->actingAs($admin)->get(route('questions')); $response->assertOk(); $user = User::factory()->create(); $response = $this->actingAs($user)->get(route('questions')); $response->assertForbidden(); $response = $this->get(route('questions')); $response->assertForbidden(); } public function testAdminCanAndOthersCannotAccessQuizzesPage() { $admin = User::factory()->admin()->create(); $response = $this->actingAs($admin)->get(route('quizzes')); $response->assertOk(); $user = User::factory()->create(); $response = $this->actingAs($user)->get(route('quizzes')); $response->assertForbidden(); $response = $this->get(route('quizzes')); $response->assertForbidden(); } public function testAdminCanAndOthersCannotAccessTestsPage() { $admin = User::factory()->admin()->create(); $response = $this->actingAs($admin)->get(route('tests')); $response->assertOk(); $user = User::factory()->create(); $response = $this->actingAs($user)->get(route('tests')); $response->assertForbidden(); $response = $this->get(route('tests')); $response->assertForbidden(); }}
Note: for every test that needs to query DB don't forget to add the
RefreshDatabase
trait.
For every test method here we do three assertions:
Now we launch php artisan test
:
That's it. Like this quickly we have added some tests to our application.