I am new to Laravel and I am having an issue to write a test function that asserts that the HTTP response of my welcome page is 200 knowing that I have EN and FR locales defined, meaning that the test should test both localhost:8000/en and localhost:8000/fr.
This is my exampletest.php:
<?php namespace TestsFeature; use AppHttpMiddlewareSetLanguage; use IlluminateFoundationTestingRefreshDatabase; use TestsTestCase; class ExampleTest extends TestCase { /** * A basic test example. * * @return void */ public function testBasicTest() { $response = $this->get('/'); $response->assertStatus(301); } public function test_getRedirected_DefaultedEnglish_WelcomePage() { $response = $this->get('/en'); $response->assertStatus(200); } public function test_getRedirected_French_WelcomePage() { $response = $this->get('/fr'); $response->assertStatus(200); } }
I don’t like writing the code twice for both /en and /fr.
This is my web.php:
<?php use IlluminateSupportFacadesRoute; use IlluminateSupportFacadesApp; use IlluminateSupportFacadesAuth; Route::redirect('/', 'en', 301); Route::group(['prefix' => '{lang}', 'where' => ['lang' => '[a-zA-Z]{2}'], 'middleware' => 'setlanguage'], function() { Auth::routes(); Route::get('/','AppHttpControllerswelcomeController@index')->name('welcome'); });
And i have written my localization middleware below:
<?php namespace AppHttpMiddleware; use Closure; use IlluminateHttpRequest; use IlluminateSupportFacadesApp; class SetLanguage { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { App::setLocale($request->lang); return $next($request); } }
I would appreciate your help on the above. I believe the test should be dynamic.
Thank you in advance..
Advertisement
Answer
I don’t think there’s any way around repeating yourself if you want to test multiple locales. But there’s no requirement to put each test in a separate method. This may work, but I’ve never done testing on multiple locales in my applications.
public function provideLocales(): array { return [ "english" => ["en"], "francais" => ["fr"], ]; } /** * @dataProvider provideLocales */ public function testWelcomePage($locale): void { $this->app->setLocale($locale); $this->get(route("welcome")) ->assertStatus(200); }
You could take this further and actually check that the localized content is being served correctly.
public function provideLocales(): array { return [ "english" => ["en", "welcome"], "francais" => ["fr", "bienvenue"], ]; } /** * @dataProvider provideLocales */ public function testWelcomePageContents($locale, $text): void { $this->app->setLocale($locale); $this->get(route("welcome")) ->assertStatus(200) ->assertSeeText($text); }