DatabaseLearn To Create Unit Tests and Migrate Databases in Laravel

Learn To Create Unit Tests and Migrate Databases in Laravel

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Laravel is an increasingly popular PHP framework that can help you develop better, more sustainable code in a shorter amount of time. Although the first part of this article explained the basic features of Laravel, this part will cover more advanced techniques, such as application testing and deployment. Some of the features that will be shown in the following sections are: installing sample data, database migrations, writing unit tests, and application deployment.

Database Seeding in Laravel

Database seeding is the process of adding the sample test data into the database. That process is made simple by using Laravel’s built-in seeding class. For example, let’s seed the table with user data; it is done by creating a new seeder class that inherits the default DatabaseSeeder class in the database/seeds folder:

<?php
class UserSeeder extends DatabaseSeeder {

   public function run()
   {
      $users = array(
               array(
                        "email" => "login@email.com",
                        "password" => Hash::make("test123"),
               )
      );
	  
      foreach ($users as $user) {
         User::create($user);
      }
   }
}

By reading the preceding code, you can see the following details:

  • All code is inside the run function.
  • $users is an array of arrays containing test data (each array corresponds to one row in the table and array keys are column names).

After creating the UserSeeder class, we need to include it in the DatabaseSeeder class by adding the following line of code to the DatabaseSeeder run function:

$this->call("UserSeeder");

After that, you are ready to run the seeder. Open the command prompt, navigate to your Laravel project folder, and execute the following command:

php artisan db:seed

The data will be in the database in a blink of an eye.

Database Migrations in Laravel

Migrations act like version control software for the database, allowing the developers to modify the database schema and stay up to date on the current schema state. Laravel migration classes are located in the database/migrations directory and use the Schema builder to programmatically create and delete tables.

A database migration extends the Migration class and has two functions: up and down:

<?php

use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration {

   // Run the migration
   public function up()
   {
      Schema::create('user', function($t) {
         $t->increments('user_id'); // Primary key
         $t->string('email'); // email field
         $t->string('password'); // password field
         $t->boolean('is_active')->default(1); // is active field where default value is 1
         $t->timestamps(); // created_at and updated_at timestamps
      });
   }

   // Reverse the migration
   public function down()
   {
      Schema::drop('user');
   }

}

Migrations are run by opening the command prompt, navigating to your Laravel project folder, and executing the following command:

php artisan migrate:make create_users_table
php artisan migrate

To roll back the last migration, do the following:

php artisan migrate:rollback

To roll back all migrations, execute this command:

php artisan migrate:reset

Unit Testing in Laravel

Unit testing is a software testing method where individual units of code are tested to see whether they are ready to be used in production. Laravel is built with unit testing support; PHPUnit is included out of the box. Also, additional libraries are included to allow you to manipulate views and simulate a web browser during testing.

To create a unit test, create a new class that extends TestCase class in the app/tests directory:

class MyFirstTest extends TestCase {
   // Write testing functions here
}

Because the tests are database-agnostic (meaning that they can work with any database driver), we need to do the database schema migration before running the test:

class TestCase extends IlluminateFoundationTestingTestCase {

   // Prepare the test
   public function setUp()
   {
      parent::setUp();

      $this->prepareForTests();
   }

   // Create the application
   public function createApplication()
   {
      $unitTesting = true;

      $testEnvironment = 'testing';

      return require __DIR__.'/../../bootstrap/start.php';
   }

   // Migrate the database
   private function prepareForTests()
   {
      Artisan::call('migrate');
   }

}

Now, we are ready to write a test. Let’s see an example where we test whether the username is required and whether the correct error message is shown:

public function MyFirstTest()
{
   // Create a new User
   $user = new User;
   $user->email = "login@email.com";
   $user->password = "password";

   // User should not save
   $this->assertFalse($user->save());

   // Save the errors
   $errors = $user->errors()->all();

   // There should be 1 error
   $this->assertCount(1, $errors);

   // The username error should be set
   $this->assertEquals($errors[0], "The username field is required.");
}

Note that assertion functions are used to test for values. For example, if the assertFalse function finds a value that is “true”, the test would fail. For more information on assertion functions and other testing functions, check this page.

Deploying Your Laravel Application

Laravel provides quick application deployment by using Laravel Forge. Although it is a paid service ($10 per month), it enables developers to quickly configure servers on DigitalOcean, Linode, Rackspace, and Amazon EC2. Forge also has many advanced features, such as deployment from the Git repository or sub-domain configuration.

Even if you are working without Laravel Forge, there are features, such as different application configuration for local and production environment, that will help you speed up the development process.

Conclusion

Laravel’s testing features provide solutions to many common problems of large web application development. These features prove that this framework can be used for small projects as well as for large ones.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories