-
Notifications
You must be signed in to change notification settings - Fork 7
Laravel Example
The following is an example Laravel application that is tested using Dredd and dredd-hooks-php.
It shows how dredd-hooks-php can be utilized to seed a database for API endpoints being tested by Dredd.
All of the files referenced in this section assume the root directory is examples/laravel
The laravel.apib
file
# My Api
## GET /user
+ Response 200 (application/json;charset=utf-8)
{
"user": {
"name": "John Doe",
"age": 22
}
}
## GET /users
+ Response 200 (application/json;charset=utf-8)
{
"users": [
{
"name": "Dom",
"email": "[email protected]"
}
]
}
The laravel routes file (app/Http/routes.php
)
<?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
use App\User;
use Illuminate\Http\Response;
Route::get('/', function () {
return view('welcome');
});
Route::get('/user', function () {
$data = json_encode([
'user' => [
'name' => 'John Doe',
'age' => 22
]
]);
return (new Response($data, 200))->header('Content-Type', 'application/json;charset=utf-8');
});
Route::get('/users', function() {
$users = User::all();
return (new Response(['users' => $users], 200))->header('Content-Type', 'application/json;charset=utf-8');
});
This file defines the two routes expected in the api blueprint file. As you can see, the /user
endpoint has the output hardcoded. The /users
endpoint however retrieves data from the database. In order to seed the database before Dredd hits the endpoint, we can use a before hook.
The following hookfile uses Laravel's built in factory function to seed the database.
Here is the hookfile (tests/dredd/hooks/hookfile.php
)
<?php
use Dredd\Hooks;
use Illuminate\Support\Facades\Artisan;
require __DIR__ . '/../../../vendor/autoload.php';
$app = require __DIR__ . '/../../../bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
Hooks::beforeEach(function (&$transaction) use ($app) {
$app->make('db')->beginTransaction();
});
Hooks::afterEach(function (&$transaction) use ($app) {
$app->make('db')->rollback();
});
Hooks::before('/users > GET', function(&$transaction) {
factory(\App\User::class)->create([
'name' => 'Dom',
'email' => '[email protected]',
]
);
});
-
Install dredd globally
npm install -g dredd
-
Clone the repository
git clone https://github.com/ddelnano/dredd-hooks-php.git
-
Change into the
examples/laravel
directory. -
Install the dependencies with composer
composer install
-
Run dredd with dredd-hooks-php
dredd ./laravel.apib http://localhost:8001 --server "php -S 0.0.0.0:8001 -t public/" --language vendor/bin/dredd-hooks-php --hookfiles tests/dredd/hooks/hookfile.php