0
0
Laravelframework~30 mins

Database testing (RefreshDatabase) in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Database testing with RefreshDatabase in Laravel
📖 Scenario: You are building a simple Laravel application that stores information about books. You want to write tests that check if the database correctly saves and retrieves book data. To keep your tests clean and isolated, you will use Laravel's RefreshDatabase trait to reset the database before each test.
🎯 Goal: Write a Laravel test class that uses the RefreshDatabase trait. Create a test that inserts a book record into the database and verifies it exists.
📋 What You'll Learn
Create a Laravel test class named BookTest
Use the RefreshDatabase trait in the test class
Write a test method named test_book_can_be_created
Insert a book with title 'The Great Gatsby' and author 'F. Scott Fitzgerald'
Assert the database has the inserted book record
💡 Why This Matters
🌍 Real World
Database testing is essential to ensure your application stores and retrieves data correctly. Using RefreshDatabase keeps tests isolated and reliable.
💼 Career
Many Laravel developer roles require writing automated tests to maintain code quality and prevent bugs in database operations.
Progress0 / 4 steps
1
Create the test class with namespace and imports
Create a Laravel test class named BookTest inside the Tests\Feature namespace. Import Tests\TestCase and Illuminate\Foundation\Testing\RefreshDatabase. Define the class extending TestCase.
Laravel
Need a hint?

Remember to declare the namespace and import the RefreshDatabase trait. Use the trait inside the class.

2
Add the test method skeleton
Inside the BookTest class, add a public method named test_book_can_be_created with no parameters. Leave the method body empty for now.
Laravel
Need a hint?

Define a public function with the exact name test_book_can_be_created inside the class.

3
Insert a book record into the database
Inside the test_book_can_be_created method, insert a new record into the books table with title set to 'The Great Gatsby' and author set to 'F. Scott Fitzgerald' using Laravel's DB::table('books')->insert() method. Import the DB facade at the top.
Laravel
Need a hint?

Use DB::table('books')->insert() with an array containing the exact keys and values.

4
Assert the book record exists in the database
Still inside the test_book_can_be_created method, add an assertion using $this->assertDatabaseHas('books', [...]) to check that the books table contains a record with title 'The Great Gatsby' and author 'F. Scott Fitzgerald'.
Laravel
Need a hint?

Use $this->assertDatabaseHas() with the exact table name and data array.