Skip to content

Instantly share code, notes, and snippets.

@paulund
Last active Dec 17, 2017
Embed
What would you like to do?
Example of smoke testing guest URLs in a Laravel application
<?php
/**
* @param $url
*
* @return mixed
*/
private function convertMapping($url)
{
foreach($this->dynamicMappings as $mapping => $modelClass)
{
$stringMapping = '{'.$mapping.'}';
if(strpos($url, $stringMapping) !== false) {
factory($modelClass)->create();
return str_replace($stringMapping, app($modelClass)->first()->slug, $url);
}
}
return $url;
}
<?php
protected $dynamicMappings = [
'tutorialSlug' => Tutorial::class,
'postSlug' => Post::class
];
<?php
private function getGuestRoutes()
{
return array_filter(app(Router::class)->getRoutes()->getRoutes(), function ($route) {
$middleware = $route->middleware();
return in_array('guest', $middleware) &&
strpos($route->uri(), '_dusk') === false ? $route : false;
});
}
<?php
namespace Tests\Feature\SmokeTests;
use App\Models\Post;
use App\Models\Tutorial;
use Illuminate\Routing\Router;
use Tests\TestCase;
class SmokeGuestTest extends TestCase
{
protected $dynamicMappings = [
'tutorialSlug' => Tag::class,
'postSlug' => Post::class
];
public function testCheckGuestRoutes()
{
foreach($this->getGuestRoutes() ?? [] as $route) {
$url = $this->convertMapping( $route->uri );
$response = $this->get($url);
$response->assertStatus(200);
}
}
/**
* Get all the urls that can be accessed by a guest user
*/
private function getGuestRoutes()
{
return array_filter(app(Router::class)->getRoutes()->getRoutes(), function ($route) {
$middleware = $route->middleware();
return in_array('guest', $middleware) &&
strpos($route->uri(), '_dusk') === false ? $route : false;
});
}
/**
* @param $url
*
* @return mixed
*/
private function convertMapping($url)
{
foreach($this->dynamicMappings as $mapping => $modelClass)
{
$stringMapping = '{'.$mapping.'}';
if(strpos($url, $stringMapping) !== false) {
factory($modelClass)->create();
return str_replace($stringMapping, app($modelClass)->first()->slug, $url);
}
}
return $url;
}
}
<?php
// Guest middleware
Route::group(['middleware' => ['guest']], function(){
// Home page
Route::get('/', 'HomeController@index');
// Tutorials
Route::get('/tutorials', 'TutorialController@index');
Route::get('/tutorials/{tutorialSlug}', 'TagsController@show');
// Blog Post
Route::get('/{postSlug}', 'PostController@show');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment