Skip to content

Instantly share code, notes, and snippets.

@paulund
Last active April 12, 2024 15:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulund/54f97933b4c93abd2f6bc9c0c776ccbf to your computer and use it in GitHub Desktop.
Save paulund/54f97933b4c93abd2f6bc9c0c776ccbf to your computer and use it in GitHub Desktop.
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