ブラウザテストを簡単に実行する方法: Laravel Duskの活用
※ 当ブログにはプロモーションが含まれています
Laravel Duskは、Laravelアプリケーションのブラウザテストを簡単に実行できる公式パッケージです。実際のブラウザを使用してエンドツーエンドテストを行うことで、ユーザーの操作を忠実に再現したテストが可能になります。
1. Laravel Duskとは
Laravel DuskはChromeDriverを使用してHeadlessブラウザでのテストを実行するツールです。JavaScriptが動作する環境でのテストも可能で、SPAやAjaxを多用するアプリケーションのテストに最適です。
2. インストール
Composerを使用してDuskをインストールします:
composer require --dev laravel/dusk
php artisan dusk:install
3. 基本的な使用方法
テストの作成
php artisan dusk:make LoginTest
テストの記述例
<?php namespace Tests\Browser; use Illuminate\Foundation\Testing\DatabaseMigrations; use Laravel\Dusk\Browser; use Tests\DuskTestCase; class LoginTest extends DuskTestCase { public function testBasicLogin() { $this->browse(function (Browser $browser) { $browser->visit('/login') ->type('email', 'user@example.com') ->type('password', 'password') ->press('Login') ->assertPathIs('/dashboard') ->assertSee('Welcome'); }); } }
4. 主要な機能
要素の操作
// 入力フィールドへの入力 $browser->type('name', 'John Doe'); // ボタンのクリック $browser->click('#submit-button'); // セレクトボックスの選択 $browser->select('country', 'Japan'); // チェックボックスの操作 $browser->check('terms'); $browser->uncheck('newsletter');
アサーション
// テキストの存在確認 $browser->assertSee('Hello World'); // URLの確認 $browser->assertPathIs('/dashboard'); // 要素の存在確認 $browser->assertPresent('#success-message'); // フォームフィールドの値確認 $browser->assertInputValue('email', 'user@example.com');
待機処理
// 要素が表示されるまで待機 $browser->waitFor('#loading-complete'); // テキストが表示されるまで待機 $browser->waitForText('Data loaded'); // JavaScriptの実行完了まで待機 $browser->waitUntil('typeof window.app !== "undefined"');
5. 実践的なテスト例
フォーム送信テスト
public function testContactFormSubmission()
{
$this->browse(function (Browser $browser) {
$browser->visit('/contact')
->type('name', 'Test User')
->type('email', 'test@example.com')
->type('message', 'This is a test message')
->press('Send Message')
->waitForText('Thank you for your message')
->assertSee('Thank you for your message');
});
}
ファイルアップロードテスト
public function testFileUpload()
{
$this->browse(function (Browser $browser) {
$browser->visit('/upload')
->attach('document', storage_path('test-files/sample.pdf'))
->press('Upload')
->waitFor('.upload-success')
->assertSee('File uploaded successfully');
});
}
6. 設定とカスタマイズ
環境設定
.env.dusk.localファイルでテスト環境を設定:
APP_URL=http://localhost:8000 DB_CONNECTION=sqlite DB_DATABASE=:memory:
ブラウザオプションのカスタマイズ
// tests/DuskTestCase.php
protected function driver()
{
$options = (new ChromeOptions)->addArguments([
'--disable-gpu',
'--headless',
'--window-size=1920,1080',
]);
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
)
);
}
ベストプラクティス
1. Page Objectパターンの使用
// tests/Browser/Pages/LoginPage.php
class LoginPage extends Page
{
public function url()
{
return '/login';
}
public function elements()
{
return [
'@email' => 'input[name="email"]',
'@password' => 'input[name="password"]',
'@submit' => 'button[type="submit"]',
];
}
public function login($email, $password)
{
return $this->type('@email', $email)
->type('@password', $password)
->click('@submit');
}
}
2. データベースの初期化
use Illuminate\Foundation\Testing\DatabaseMigrations;
class UserTest extends DuskTestCase
{
use DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
// テストデータの準備
User::factory()->create([
'email' => 'test@example.com',
'password' => bcrypt('password'),
]);
}
}
3. スクリーンショットの活用
public function testFailureWithScreenshot()
{
$this->browse(function (Browser $browser) {
$browser->visit('/complex-page')
->screenshot('before-interaction')
->click('#complex-button')
->screenshot('after-interaction')
->assertSee('Expected Result');
});
}
7. トラブルシューティング
よくある問題と解決方法
- ChromeDriverのバージョン不一致
php artisan dusk:chrome-driver --detect
- タイムアウトエラー
// 待機時間を延長
$browser->waitFor('#slow-element', 30);
- 要素が見つからない
// より具体的なセレクターを使用 $browser->assertPresent('div.container > .specific-class');
8. まとめ
Laravel Duskを使用することで、ブラウザベースの包括的なテストを効率的に実装できます。JavaScriptが動作する実際のブラウザ環境でのテストにより、ユーザー体験に近い形でのテストが可能になり、アプリケーションの品質向上に大きく貢献します。
継続的インテグレーション(CI)環境での実行も容易で、開発チーム全体でのテスト自動化を推進する強力なツールといえるでしょう。
9. おすすめ教材📘
Laravelの教科書 バージョン10対応 [ 加藤 じゅんこ ] 価格:3300円 |
![]()
