Courses

Creating a Quiz System with Laravel 10 + Livewire 3: Step-by-Step

Quizzes Test

In this last lesson, we will have another test for Quizzes form.

As always we need a factory.

php artisan make:factory QuizFactory

database/factories/QuizFactory.php:

use Illuminate\Support\Str;
 
class QuizFactory extends Factory
{
public function definition(): array
{
$title = $this->faker->sentence();
$slug = Str::slug($title);
 
return [
'title' => $title,
'slug' => $slug,
'description' => fake()->paragraph(),
'published' => false,
'public' => false,
];
}
}

And the feature test.

php artisan make:test Livewire/QuizzesTest

tests/Feature/Livewire/QuizzesTest.php:

use App\Models\User;
use App\Models\Quiz;
use Livewire\Livewire;
use App\Models\Question;
use App\Livewire\Quiz\QuizForm;
use Illuminate\Foundation\Testing\RefreshDatabase;
 
class QuizzesTest extends TestCase
{
use RefreshDatabase;
 
public function testAdminCanCreateQuiz()
{
$this->actingAs(User::factory()->admin()->create());
 
Livewire::test(QuizForm::class)
->set('title', 'quiz title')
->call('save')
->assertHasNoErrors(['title', 'slug', 'description', 'published', 'public', 'questions'])
->assertRedirect(route('quizzes'));
 
$this->assertDatabaseHas('quizzes', [
'title' => 'quiz title',
]);
}
 
public function testTitleIsRequired()
{
$this->actingAs(User::factory()->admin()->create());
 
Livewire::test(QuizForm::class)
->set('title', '')
->call('save')
->assertHasErrors(['title' => 'required']);
}
 
public function testAdminCanEditQuiz()
{
$this->actingAs(User::factory()->admin()->create());
 
$quiz = Quiz::factory()
->has(Question::factory())
->create();
 
Livewire::test(QuizForm::class, [$quiz])
->set('title', 'new quiz')
->set('published', true)
->call('save')
->assertSet('published', true)
->assertHasNoErrors(['title', 'slug', 'description', 'published', 'public', 'questions']);
 
$this->assertDatabaseHas('quizzes', [
'title' => 'new quiz',
'published' => true,
]);
}
}

These tests are very similar to the Questions. For the quiz edit, we also check if setting published to true is correct.

quizzes tests

avatar

Nice course and helpful 👍

Thanks 🌹

avatar
You can use Markdown
avatar

thanks

avatar
You can use Markdown
avatar

Can you upgrade this course for Livewire v3?

avatar
You can use Markdown
avatar

Thank you.

avatar
You can use Markdown
avatar
You can use Markdown