Readouble

Laravel 5.4 ブラウザテスト(Laravel Dusk)

イントロダクションIntroduction

Laravel Dusk(ダースク:夕暮れ)は、利用が簡単なブラウザの自動操作/テストAPIを提供します。デフォルトのDuskは皆さんのマシンへ、JDKやSeleniumのインストールを求めません。代わりにDuskはスタンドアローンのChromeDriverを使用します。しかし、好みのSeleniumコンパチドライバも自由に使用することもできます。Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your machine. Instead, Dusk uses a standalone ChromeDriver[https://sites.google.com/a/chromium.org/chromedriver/home] installation. However, you are free to utilize any other Selenium compatible driver you wish.

インストールInstallation

使用を開始するには、laravel/duskコンポーサ依存パッケージをプロジェクトへ追加します。To get started, you should add the laravel/dusk Composer dependency to your project:

composer require --dev laravel/dusk

Duskをインストールしたら、Laravel\Dusk\DuskServiceProviderサービスプロバイダを登録してください。Duskは他のユーザーとしてのログイン機能を可能にしてしまうので、利用可能な環境を限定するため、AppServiceProviderregisterメソッド中でプロバイダーを登録します。Once Dusk is installed, you should register the Laravel\Dusk\DuskServiceProvider service provider. You should register the provider within the register method of your AppServiceProvider in order to limit the environments in which Dusk is available, since it exposes the ability to log in as other users:

use Laravel\Dusk\DuskServiceProvider;

/**
 * 全アプリケーションサービスの登録
 *
 * @return void
 */
public function register()
{
    if ($this->app->environment('local', 'testing')) {
        $this->app->register(DuskServiceProvider::class);
    }
}

次に、dusk:install Artisanコマンドを実行します。Next, run the dusk:install Artisan command:

php artisan dusk:install

testディレクトリ中に、サンプルテストを含んだBrowserディレクトリが作成されます。次に、.envファイルでAPP_URL環境変数を指定します。この値は、ブラウザからアクセスするアプリケーションで使用するURLと一致させます。A Browser directory will be created within your tests directory and will contain an example test. Next, set the APP_URL environment variable in your .env file. This value should match the URL you use to access your application in a browser.

テストを実行するには、dusk Artisanコマンドを使います。duskコマンドには、phpunitコマンドが受け付ける引数を全て指定できます。To run your tests, use the dusk Artisan command. The dusk command accepts any argument that is also accepted by the phpunit command:

php artisan dusk

他ブラウザの使用Using Other Browsers

デフォルトのDuskは、Google ChromeとスタンドアローンのChromeDriverをブラウザテスト実行に使用します。しかし、自身のSeleniumサーバを起動し、希望するブラウザに対しテストを実行することもできます。By default, Dusk uses Google Chrome and a standalone ChromeDriver[https://sites.google.com/a/chromium.org/chromedriver/home] installation to run your browser tests. However, you may start your own Selenium server and run your tests against any browser you wish.

開始するには、アプリケーションのベースDuskテストケースである、tests/DuskTestCase.phpファイルを開きます。このファイルの中の、startChromeDriverメソッド呼び出しを削除してください。これにより、ChromeDriverの自動起動を停止します。To get started, open your tests/DuskTestCase.php file, which is the base Dusk test case for your application. Within this file, you can remove the call to the startChromeDriver method. This will stop Dusk from automatically starting the ChromeDriver:

/**
 * Duskテスト実行準備
 *
 * @beforeClass
 * @return void
 */
public static function prepare()
{
    // static::startChromeDriver();
}

次に、皆さんが選んだURLとポートへ接続するために、driverメソッドを変更します。WebDriverに渡すべき、"desired capabilities"を更新することもできます。Next, you may simply modify the driver method to connect to the URL and port of your choice. In addition, you may modify the "desired capabilities" that should be passed to the WebDriver:

/**
 * RemoteWebDriverインスタンスの生成
 *
 * @return \Facebook\WebDriver\Remote\RemoteWebDriver
 */
protected function driver()
{
    return RemoteWebDriver::create(
        'http://localhost:4444/wd/hub', DesiredCapabilities::phantomjs()
    );
}

ChromeDriverオプションChromeDriver Options

ChromeDriverセッションをカスタマイズするには、DuskTestCaseクラスのdriverメソッドを変更してください。To customize the ChromeDriver session, you may modify the driver method of the DuskTestCase class:

use Facebook\WebDriver\Chrome\ChromeOptions;

/**
 * RemoteWebDriverインスタンスの生成
 *
 * @return \Facebook\WebDriver\Remote\RemoteWebDriver
 */
protected function driver()
{
    $options = (new ChromeOptions)->addArguments(['--headless']);

    return RemoteWebDriver::create(
        'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
            ChromeOptions::CAPABILITY, $options
        )
    );
}

利用の開始Getting Started

テストの生成Generating Tests

Duskのテストを生成するには、dusk:make Artisanコマンドを使います。生成されたテストは、tests/Browserディレクトリへ設置されます。To generate a Dusk test, use the dusk:make Artisan command. The generated test will be placed in the tests/Browser directory:

php artisan dusk:make LoginTest

テストの実行Running Tests

ブラウザテストを実行するには、dusk Artisanコマンドを使用します。To run your browser tests, use the dusk Artisan command:

php artisan dusk

PHPUnitテストランナが通常受け付ける引数は、duskコマンドでも指定できます。たとえば、指定したグループのテストのみを実行するなどです。The dusk command accepts any argument that is normally accepted by the PHPUnit test runner, allowing you to only run the tests for a given group[https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.group], etc:

php artisan dusk --group=foo

ChromeDriverの手動起動Manually Starting ChromeDriver

デフォルトのDuskは、ChromeDriverを自動的に起動しようとします。特定のシステムで自動起動しない場合は、duskコマンドを実行する前に手動でChromeDriverを起動することもできます。ChromeDriverを手動起動する場合は、tests/DuskTestCase.phpファイルの以下の行をコメントアウトしてください。By default, Dusk will automatically attempt to start ChromeDriver. If this does not work for your particular system, you may manually start ChromeDriver before running the dusk command. If you choose to start ChromeDriver manually, you should comment out the following line of your tests/DuskTestCase.php file:

/**
 * Duskテスト実行準備
 *
 * @beforeClass
 * @return void
 */
public static function prepare()
{
    // static::startChromeDriver();
}

また、ChromeDriverを9515以外のポートで起動した場合、同じクラスのdriverメソッドを変更する必要があります。In addition, if you start ChromeDriver on a port other than 9515, you should modify the driver method of the same class:

/**
 * RemoteWebDriverインスタンスの生成
 *
 * @return \Facebook\WebDriver\Remote\RemoteWebDriver
 */
protected function driver()
{
    return RemoteWebDriver::create(
        'http://localhost:9515', DesiredCapabilities::chrome()
    );
}

環境の処理Environment Handling

テスト実行時に独自の環境ファイルを強制的に使用させるには、プロジェクトのルートに.env.dusk.{environment}ファイルを作成します。たとえば、local環境からduskコマンドを起動する場合は、.env.dusk.localファイルを作成します。To force Dusk to use its own environment file when running tests, create a .env.dusk.{environment} file in the root of your project. For example, if you will be initiating the dusk command from your local environment, you should create a .env.dusk.local file.

テストを実行すると、Duskは.envファイルをバックアップし、皆さんのDusk環境を.envへリネームします。テストが完了したら、.envファイルをリストアします。When running tests, Dusk will back-up your .env file and rename your Dusk environment to .env. Once the tests have completed, your .env file will be restored.

ブラウザの生成Creating Browsers

手始めに、アプリケーションへログインできることを確認するテストを書いてみましょう。テストを生成したら、ログインページへ移動し、認証情報を入力し、"Login"ボタンをクリックするように変更します。ブラウザインスタンスを生成するには、browserメソッドを呼び出します。To get started, let's write a test that verifies we can log into our application. After generating a test, we can modify it to navigate to the login page, enter some credentials, and click the "Login" button. To create a browser instance, call the browse method:

<?php

namespace Tests\Browser;

use App\User;
use Tests\DuskTestCase;
use Laravel\Dusk\Chrome;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class ExampleTest extends DuskTestCase
{
    use DatabaseMigrations;

    /**
     * 基本的なブラウザテスト例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $user = factory(User::class)->create([
            'email' => 'taylor@laravel.com',
        ]);

        $this->browse(function ($browser) use ($user) {
            $browser->visit('/login')
                    ->type('email', $user->email)
                    ->type('password', 'secret')
                    ->press('Login')
                    ->assertPathIs('/home');
        });
    }
}

上記の例のように、browseメソッドはコールバックを引数に受けます。 Duskによりブラウザインスタンスは自動的にこのコールバックに渡され、このオブジェクトで、アプリケーションに対する操作やアサートを行います。As you can see in the example above, the browse method accepts a callback. A browser instance will automatically be passed to this callback by Dusk and is the main object used to interact with and make assertions against your application.

lightbulb">Tip!! このテストは、make:auth Artisanコマンドにより生成される、ログインスクリーンのテストに使用できます。{tip} This test can be used to test the login screen generated by the make:auth Artisan command.

複数ブラウザの生成Creating Multiple Browsers

テストを行うために複数のブラウザが必要なこともあります。たとえば、Webソケットを使用するチャットスクリーンをテストするためには、複数のブラウザが必要でしょう。複数ブラウザを生成するには、単にbrowseメソッドに指定するコールバックの引数で、一つ以上のブラウザを指定するだけです。Sometimes you may need multiple browsers in order to properly carry out a test. For example, multiple browsers may be needed to test a chat screen that interacts with websockets. To create multiple browsers, simply "ask" for more than one browser in the signature of the callback given to the browse method:

$this->browse(function ($first, $second) {
    $first->loginAs(User::find(1))
          ->visit('/home')
          ->waitForText('Message');

    $second->loginAs(User::find(2))
           ->visit('/home')
           ->waitForText('Message')
           ->type('message', 'Hey Taylor')
           ->press('Send');

    $first->waitForText('Hey Taylor')
          ->assertSee('Jeffrey Way');
});

認証Authentication

認証が必要なページのテストはよくあります。毎回テストのたびにログインスクリーンを操作しなくても済むように、DuskのloginAsメソッドを使ってください。loginAsメソッドはユーザーIDかユーザーモデルインスタンスを引数に取ります。Often, you will be testing pages that require authentication. You can use Dusk's loginAs method in order to avoid interacting with the login screen during every test. The loginAs method accepts a user ID or user model instance:

$this->browse(function ($first, $second) {
    $first->loginAs(User::find(1))
          ->visit('/home');
});

Note: note loginAsメソッドを使用後、そのファイルに含まれるすべてのテストに対し、ユーザーセッションは保持されます。{note} After using the loginAs method, the user session will be maintained for all tests within the file.

要素の操作Interacting With Elements

リンクのクリックClicking Links

リンクをクリックするには、ブラウザインスタンスのclickLinkメソッドを使います。clickLinkメソッドは指定した表示テキストのリンクをクリックします。To click a link, you may use the clickLink method on the browser instance. The clickLink method will click the link that has the given display text:

$browser->clickLink($linkText);

Note: note このメソッドはjQueryを操作します。jQueryがそのページで使用不可能な場合、Duskは自動的にそのページへ挿入し、テストの中に使用します。{note} This method interacts with jQuery. If jQuery is not available on the page, Dusk will automatically inject it into the page so it is available for the test's duration.

テキスト、値、属性Text, Values, & Attributes

値の取得/設定Retrieving & Setting Values

Duskは現在表示されているテキスト、値、ページ要素の属性を操作する、数多くのメソッドを提供します。たとえば、指定したセレクタに一致する要素の「値(value)」を取得するには、valueメソッドを使用します。Dusk provides several methods for interacting with the current display text, value, and attributes of elements on the page. For example, to get the "value" of an element that matches a given selector, use the value method:

// 値の取得
$value = $browser->value('selector');

// 値の設定
$browser->value('selector', 'value');

テキストの取得Retrieving Text

textメソッドは、指定したセレクタに一致する要素の表示テキストを取得します。The text method may be used to retrieve the display text of an element that matches the given selector:

$text = $browser->text('selector');

属性の取得Retrieving Attributes

最後のattributeメソッドは、セレクタに一致する要素の属性を取得します。Finally, the attribute method may be used to retrieve an attribute of an element matching the given selector:

$attribute = $browser->attribute('selector', 'value');

フォームの使用Using Forms

値のタイプTyping Values

Duskはフォームと入力要素を操作する、様々なメソッドを提供しています。最初に、入力フィールドへテキストをタイプする例を見てみましょう。Dusk provides a variety of methods for interacting with forms and input elements. First, let's take a look at an example of typing text into an input field:

$browser->type('email', 'taylor@laravel.com');

必要であれば受け付けますが、typeメソッドにはCSSセレクタを渡す必要がないことに注意してください。CSSセレクタが指定されない場合、Duskはname属性に指定された入力フィールドを探します。最終的に、Duskは指定されたname属性を持つtextareaを見つけようとします。Note that, although the method accepts one if necessary, we are not required to pass a CSS selector into the type method. If a CSS selector is not provided, Dusk will search for an input field with the given name attribute. Finally, Dusk will attempt to find a textarea with the given name attribute.

入力の値を「消去(clear)」する場合は、clearメソッドを使用します。You may "clear" the value of an input using the clear method:

$browser->clear('email');

ドロップダウンDropdowns

ドロップダウンの選択ボックスから値を選ぶには、selectメソッドを使います。typeメソッドと同様に、selectメソッドも完全なCSSセレクタは必要ありません。selectメソッドに引数を指定するとき、表示テキストの代わりに、オプション値を渡します。To select a value in a dropdown selection box, you may use the select method. Like the type method, the select method does not require a full CSS selector. When passing a value to the select method, you should pass the underlying option value instead of the display text:

$browser->select('size', 'Large');

第2引数を省略した場合、ランダムにオプションを選択します。You may select a random option by omitting the second parameter:

$browser->select('size');

チェックボックスCheckboxes

チェックボックスを「チェック(check)」するには、checkメソッドを使います。他の関連する多くのメソッドと同様に、完全なCSSセレクタは必要ありません。完全に一致するセレクタが見つからないと、Duskはname属性に一致するチェックボックスを探します。To "check" a checkbox field, you may use the check method. Like many other input related methods, a full CSS selector is not required. If an exact selector match can't be found, Dusk will search for a checkbox with a matching name attribute:

$browser->check('terms');

$browser->uncheck('terms');

ラジオボタンRadio Buttons

ラジオボタンのオプションを「選択」するには、radioメソッドを使用します。他の関連する多くのメソッドと同様に、完全なセレクタは必要ありません。完全に一致するセレクタが見つからない場合、Duskはnamevalue属性に一致するラジオボタンを探します。To "select" a radio button option, you may use the radio method. Like many other input related methods, a full CSS selector is not required. If an exact selector match can't be found, Dusk will search for a radio with matching name and value attributes:

$browser->radio('version', 'php7');

添付ファイルAttaching Files

attachメソッドはfile入力要素で、ファイルを指定するために使用します。他の関連する入力メソッドと同様に、完全なCSSセレクタは必要ありません。完全なセレクタが見つからなければ、Duskはname属性と一致するファイル入力を探します。The attach method may be used to attach a file to a file input element. Like many other input related methods, a full CSS selector is not required. If an exact selector match can't be found, Dusk will search for a file input with matching name attribute:

$browser->attach('photo', __DIR__.'/photos/me.png');

キーワードの使用Using The Keyboard

keysメソッドは、typeメソッドによる、指定した要素に対する通常の入力よりも、複雑な入力を提供します。たとえば、モデファイヤキーを押しながら、値を入力するなどです。以下の例では、指定したセレクタに一致する要素へ、taylorを「シフト(shift)」キーを押しながら入力します。Taylorをタイプし終えると、otwellがモデファイヤキーを押さずにタイプされます。The keys method allows you to provide more complex input sequences to a given element than normally allowed by the type method. For example, you may hold modifier keys entering values. In this example, the shift key will be held while taylor is entered into the element matching the given selector. After taylor is typed, otwell will be typed without any modifier keys:

$browser->keys('selector', ['{shift}', 'taylor'], 'otwell');

アプリケーションを構成する主要なCSSセレクタへ「ホットキー」を送ることもできます。You may even send a "hot key" to the primary CSS selector that contains your application:

$browser->keys('.app', ['{command}', 'j']);

lightbulb">Tip!! モデファイヤキーは{}文字で囲み、Facebook\WebDriver\WebDriverKeysクラスで定義されている定数を指定します。GitHubで確認できます。{tip} All modifier keys are wrapped in {} characters, and match the constants defined in the Facebook\WebDriver\WebDriverKeys class, which can be found on GitHub[https://github.com/facebook/php-webdriver/blob/community/lib/WebDriverKeys.php].

マウスの使用Using The Mouse

要素のクリックClicking On Elements

指定したセレクタに一致する要素を「クリック」するには、clickメソッドを使います。The click method may be used to "click" on an element matching the given selector:

$browser->click('.selector');

マウスオーバーMouseover

指定したセレクタに一致する要素を「マウスオーバー」したい場合は、mouseoverメソッドを使います。The mouseover method may be used when you need to move the mouse over an element matching the given selector:

$browser->mouseover('.selector');

ドラッグ&ドロップDrag & Drop

dragメソッドは指定したセレクタに一致する要素をドラッグし、もう一つのエレメントへドロップします。The drag method may be used to drag an element matching the given selector to another element:

$browser->drag('.from-selector', '.to-selector');

もしくは、特定の方向へ要素をドラッグすることもできます。Or, you may drag an element in a single direction:

$browser->dragLeft('.selector', 10);
$browser->dragRight('.selector', 10);
$browser->dragUp('.selector', 10);
$browser->dragDown('.selector', 10);

セレクタの範囲指定Scoping Selectors

特定のセレクタの中の全操作を範囲指定しつつ、多くの操作を行いたいこともあります。たとえば、いくつかのテーブル中にあるテキストが存在していることをアサートし、それからテーブル中のボタンをクリックしたい場合です。withメソッドで行なえます。withメソッドのコールバック中で行われた操作は全部、オリジナルのセレクタに対し限定されます。Sometimes you may wish to perform several operations while scoping all of the operations within a given selector. For example, you may wish to assert that some text exists only within a table and then click a button within that table. You may use the with method to accomplish this. All operations performed within the callback given to the with method will be scoped to the original selector:

$browser->with('.table', function ($table) {
    $table->assertSee('Hello World')
          ->clickLink('Delete');
});

要素の待機Waiting For Elements

広範囲に渡りJavaScriptを使用しているアプリケーションのテストでは、テストを進める前に特定の要素やデータが利用可能になるまで、「待つ(wait)」必要がしばしば起きます。Duskではこれも簡単に行えます。数多くのメソッドを使い、ページで要素が見えるようになるまで、もしくはJavaScriptの評価がtureになるまで待機できます。When testing applications that use JavaScript extensively, it often becomes necessary to "wait" for certain elements or data to be available before proceeding with a test. Dusk makes this a cinch. Using a variety of methods, you may wait for elements to be visible on the page or even wait until a given JavaScript expression evaluates to true.

待機Waiting

指定したミリ秒の間、テストをポーズしたい場合は、pauseメソッドを使用します。If you need to pause the test for a given number of milliseconds, use the pause method:

$browser->pause(1000);

セレクタの待機Waiting For Selectors

waitForメソッドはテストの実行を指定したCSSセレクタがページに表示されるまで中断します。例外が投げられるまで、デフォルトで最大5秒間テストを中断します。必要であれば、カスタムタイムアウトを秒でメソッドの第2引数として指定できます。The waitFor method may be used to pause the execution of the test until the element matching the given CSS selector is displayed on the page. By default, this will pause the test for a maximum of five seconds before throwing an exception. If necessary, you may pass a custom timeout threshold as the second argument to the method:

// セレクタを最大5秒間待つ
$browser->waitFor('.selector');

// セレクタを最大1秒待つ
$browser->waitFor('.selector', 1);

指定したセレクタがページから消えるまで待つこともできます。You may also wait until the given selector is missing from the page:

$browser->waitUntilMissing('.selector');

$browser->waitUntilMissing('.selector', 1);

利用可能時限定のセレクタScoping Selectors When Available

指定したセレクタを待ち、それからそのセレクタに一致する要素を操作したい場合もよくあります。たとえば、モーダルウィンドウが現れるまで待ち、それからそのモーダルウィンドウ上の"OK"ボタンを押したい場合です。このケースではwhenAvailableメソッドを使用します。指定したコールバック内で行われた要素操作は全て、オリジナルのセレクタに対して限定されます。Occasionally, you may wish to wait for a given selector and then interact with the element matching the selector. For example, you may wish to wait until a modal window is available and then press the "OK" button within the modal. The whenAvailable method may be used in this case. All element operations performed within the given callback will be scoped to the original selector:

$browser->whenAvailable('.modal', function ($modal) {
    $modal->assertSee('Hello World')
          ->press('OK');
});

テキストの待機Waiting For Text

指定したテキストがページに表示されるまで待ちたい場合は、waitForTextメソッドを使います。The waitForText method may be used to wait until the given text is displayed on the page:

// テキストを最大5秒間待つ
$browser->waitForText('Hello World');

// テキストを最大1秒待つ
$browser->waitForText('Hello World', 1);

リンクの待機Waiting For Links

ページに指定したリンクテキストが表示されるまで待つ場合は、waitForLinkメソッドを使います。The waitForLink method may be used to wait until the given link text is displayed on the page:

// リンクを最大5秒間待つ
$browser->waitForLink('Create');

// リンクを最大1秒間待つ
$browser->waitForLink('Create', 1);

ページロケーションの待機Waiting On The Page Location

$browser->assertPathIs('/home')のようなパスをアサートするときに、window.location.pathnameが非同期更新中の場合、アサートは失敗するでしょう。指定値のロケーションを待機するために、waitForLocationメソッドを使ってください。When making a path assertion such as $browser->assertPathIs('/home'), the assertion can fail if window.location.pathname is being updated asynchronously. You may use the waitForLocation method to wait for the location to be a given value:

$browser->waitForLocation('/secret');

ページリロードの待機Waiting for Page Reloads

ページのリロード後にアサートする必要がある場合は、waitForReloadメソッドを使ってください。If you need to make assertions after a page has been reloaded, use the waitForReload method:

$browser->click('.some-action')
        ->waitForReload()
        ->assertSee('something');

JavaScriptの評価の待機Waiting On JavaScript Expressions

指定したJavaScript式の評価がtureになるまで、テストの実行を中断したい場合も時々あります。waitUntilメソッドで簡単に行えます。このメソッドに式を渡す時に、returnキーワードや最後のセミコロンを含める必要はありません。Sometimes you may wish to pause the execution of a test until a given JavaScript expression evaluates to true. You may easily accomplish this using the waitUntil method. When passing an expression to this method, you do not need to include the return keyword or an ending semi-colon:

// 式がtureになるまで最大5秒間待つ
$browser->waitUntil('App.dataLoaded');

$browser->waitUntil('App.data.servers.length > 0');

// 式がtureになるまで最大1秒間待つ
$browser->waitUntil('App.data.servers.length > 0', 1);

コールバックによる待機Waiting With A Callback

Duskにある数多くの「待機」メソッドは、waitUsingメソッドを使用しています。このメソッドを直接利用し、コールバックがtrueを返すまで待機することができます。waitUsingメソッドは最長待ち秒数とクロージャを評価する間隔秒数、クロージャを引数に取ります。オプションとして、失敗時のメッセージを引数に取ります。Many of the "wait" methods in Dusk rely on the underlying waitUsing method. You may use this method directly to wait for a given callback to return true. The waitUsing method accepts the maximum number of seconds to wait, the interval at which the Closure should be evaluated, the Closure, and an optional failure message:

$browser->waitUsing(10, 1, function () use ($something) {
    return $something->isReady();
}, "Something wasn't ready in time.");

使用可能なアサートAvailable Assertions

Duskはアプリケーションに対する数多くのアサートを提供しています。使用できるアサートを次の表にまとめます。Dusk provides a variety of assertions that you may make against your application. All of the available assertions are documented in the table below:

アサートAssertion 説明Description
$browser->assertTitle($title)$browser->assertTitle($title) ページタイトルが指定したテキストであることをアサートする。Assert the page title matches the given text.
$browser->assertTitleContains($title)$browser->assertTitleContains($title) ページタイトルに指定したテキストが含まれることをアサートする。Assert the page title contains the given text.
$browser->assertPathBeginsWith($path)$browser->assertPathBeginsWith($path) 現在のURLが指定したパスで始まることをアサートする。Assert that the current URL path begins with given path.
$browser->assertPathIs('/home')$browser->assertPathIs('/home') 現在のパスが指定したパスと一致することをアサートする。Assert the current path matches the given path.
$browser->assertPathIsNot('/home')$browser->assertPathIsNot('/home') 現在のパスが指定したパスと一致しないことをアサートする。Assert the current path does not match the given path.
$browser->assertRouteIs($name, $parameters)$browser->assertRouteIs($name, $parameters) 現在のURLが、指定した名前付きルートのURLと一致することをアサートする。Assert the current URL matches the given named route's URL.
$browser->assertQueryStringHas($name, $value)$browser->assertQueryStringHas($name, $value) 指定したクエリパラメータが存在し、指定した値であることをアサートする。Assert the given query string parameter is present and has a given value.
$browser->assertQueryStringMissing($name)$browser->assertQueryStringMissing($name) 指定したクエリ文字列パラメータが存在しないことをアサートする。Assert the given query string parameter is missing.
$browser->assertHasQueryStringParameter($name)$browser->assertHasQueryStringParameter($name) 指定したクエリパラータが存在することをアサートする。Assert that the given query string parameter is present.
$browser->assertHasCookie($name)$browser->assertHasCookie($name) 指定したクッキーが存在することをアサートする。Assert the given cookie is present.
$browser->assertCookieValue($name, $value)$browser->assertCookieValue($name, $value) クッキーが指定した値であることをアサートする。Assert a cookie has a given value.
$browser->assertPlainCookieValue($name, $value)$browser->assertPlainCookieValue($name, $value) 暗号化されていないクッキーが指定した値であることをアサートする。Assert an unencrypted cookie has a given value.
$browser->assertSee($text)$browser->assertSee($text) ページに指定したテキストが存在することをアサートする。Assert the given text is present on the page.
$browser->assertDontSee($text)$browser->assertDontSee($text) ページに指定したテキストが存在しないことをアサートする。Assert the given text is not present on the page.
$browser->assertSeeIn($selector, $text)$browser->assertSeeIn($selector, $text) セレクタの中に指定したテキストが存在することをアサートする。Assert the given text is present within the selector.
$browser->assertDontSeeIn($selector, $text)$browser->assertDontSeeIn($selector, $text) セレクタの中に指定したテキストが存在していないことをアサートする。Assert the given text is not present within the selector.
$browser->assertSourceHas($code)$browser->assertSourceHas($code) ページに指定したソースコードが存在することをアサートする。Assert that the given source code is present on the page.
$browser->assertSourceMissing($code)$browser->assertSourceMissing($code) ページに指定したソースコードが存在しないことをアサートする。Assert that the given source code is not present on the page.
$browser->assertSeeLink($linkText)$browser->assertSeeLink($linkText) ページに指定したリンクが存在することをアサートする。Assert the given link is present on the page.
$browser->assertDontSeeLink($linkText)$browser->assertDontSeeLink($linkText) ページに指定したリンクが存在しないことをアサートする。Assert the given link is not present on the page.
$browser->assertSeeLink($link)$browser->assertSeeLink($link) 指定リンクが可視(visible)であることをアサートする。Determine if the given link is visible.
$browser->assertInputValue($field, $value)$browser->assertInputValue($field, $value) 指定した入力フィールドが指定した値であることをアサートする。Assert the given input field has the given value.
$browser->assertInputValueIsNot($field, $value)$browser->assertInputValueIsNot($field, $value) 指定した入力フィールドが指定した値でないことをアサートする。Assert the given input field does not have the given value.
$browser->assertChecked($field)$browser->assertChecked($field) 指定したチェックボックスがチェック済みであることをアサートする。Assert the given checkbox is checked.
$browser->assertNotChecked($field)$browser->assertNotChecked($field) 指定したチェックボックスがチェックされていないことをアサートする。Assert the given checkbox is not checked.
$browser->assertRadioSelected($field, $value)$browser->assertRadioSelected($field, $value) 指定したラジオフィールドが選択されていることをアサートする。Assert the given radio field is selected.
$browser->assertRadioNotSelected($field, $value)$browser->assertRadioNotSelected($field, $value) 指定したラジオフィールドが選択されていないことをアサートする。Assert the given radio field is not selected.
$browser->assertSelected($field, $value)$browser->assertSelected($field, $value) 指定したドロップダウンの指定値が選択されていることをアサートする。Assert the given dropdown has the given value selected.
$browser->assertNotSelected($field, $value)$browser->assertNotSelected($field, $value) 指定したドロップダウンの指定値が選択されていないことをアサートする。Assert the given dropdown does not have the given value selected.
$browser->assertSelectHasOptions($field, $values)$browser->assertSelectHasOptions($field, $values) 指定した配列の値が、選択可能であることをアサートする。Assert that the given array of values are available to be selected.
$browser->assertSelectMissingOptions($field, $values)$browser->assertSelectMissingOptions($field, $values) 指定した配列の値が、選択不可能であることをアサートする。Assert that the given array of values are not available to be selected.
$browser->assertSelectHasOption($field, $value)$browser->assertSelectHasOption($field, $value) 指定した値が、指定フィールドで選択可能であることをアサートする。Assert that the given value is available to be selected on the given field.
$browser->assertValue($selector, $value)$browser->assertValue($selector, $value) 指定したセレクタに一致する要素が、指定値であることをアサートする。Assert the element matching the given selector has the given value.
$browser->assertVisible($selector)$browser->assertVisible($selector) 指定したセレクタに一致する要素がビジブルであることをアサートする。Assert the element matching the given selector is visible.
$browser->assertMissing($selector)$browser->assertMissing($selector) 指定したセレクタに一致する要素がビジブルでないことをアサートする。-Assert the element matching the given selector is not visible.
$browser->assertDialogOpened($message)$browser->assertDialogOpened($message) 指定したメッセージを表示するJavaScriptダイアログが開かれていることをアサートする。Assert that a JavaScript dialog with given message has been opened.

ページPages

時にテストで、連続して実行する複雑なアクションをたくさん要求されることがあります。これにより、テストは読みづらく、また理解しづらくなります。ページに対し一つのメソッドを使うだけで、指定ページで実行されるアクションを記述的に定義できます。ページはまた、アプリケーションやシングルページで一般的なセレクタの、短縮記法を定義する方法も提供しています。Sometimes, tests require several complicated actions to be performed in sequence. This can make your tests harder to read and understand. Pages allow you to define expressive actions that may then be performed on a given page using a single method. Pages also allow you to define short-cuts to common selectors for your application or a single page.

ページの生成Generating Pages

ページオプジェクトを生成するには、dusk:page Artisanコマンドを使います。全てのページオブジェクトは、tests/Browser/Pagesディレクトリへ設置します。To generate a page object, use the dusk:page Artisan command. All page objects will be placed in the tests/Browser/Pages directory:

php artisan dusk:page Login

ページの設定Configuring Pages

デフォルトでページには、urlassertelementsの3メソッドが用意されています。urlassertメソッドは、この後説明します。elementsメソッドについては、のちほど詳細を紹介します。By default, pages have three methods: url, assert, and elements. We will discuss the url and assert methods now. The elements method will be discussed in more detail below[#shorthand-selectors].

urlメソッドThe url Method

urlメソッドでは、そのページを表すURLのパスを返します。Duskはブラウザでこのページへ移動するとき、このURLを使用します。The url method should return the path of the URL that represents the page. Dusk will use this URL when navigating to the page in the browser:

/**
 * このページのURL取得
 *
 * @return string
 */
public function url()
{
    return '/login';
}

assertメソッドThe assert Method

assertメソッドでは、ブラウザが実際に指定ページを表示した時に、確認が必要なアサーションを定義します。このメソッドで完全に行う必要はありません。ですが、もしお望みであれば自由にアサートを記述してください。記述されたアサートは、このページへ移行時に自動的に実行されます。The assert method may make any assertions necessary to verify that the browser is actually on the given page. Completing this method is not necessary; however, you are free to make these assertions if you wish. These assertions will be run automatically when navigating to the page:

/**
 * ブラウザがこのページにやって来たときのアサート
 *
 * @return void
 */
public function assert(Browser $browser)
{
    $browser->assertPathIs($this->url());
}

ページへのナビゲーションNavigating To Pages

ページの設定を終えたら、visitメソッドを使い、ページへ移行できます。Once a page has been configured, you may navigate to it using the visit method:

use Tests\Browser\Pages\Login;

$browser->visit(new Login);

既に特定のページに移動済みで、現在のテストコンテキストへそのページのセレクタとメソッドを「ロード」する必要が起きることがあります。この状況は、明示的に移動していなくても、あるボタンを押すことで指定ページへリダイレクトしてしまう場合に発生します。そうした場合は、onメソッドで、そのページをロードできます。Sometimes you may already be on a given page and need to "load" the page's selectors and methods into the current test context. This is common when pressing a button and being redirected to a given page without explicitly navigating to it. In this situation, you may use the on method to load the page:

use Tests\Browser\Pages\CreatePlaylist;

$browser->visit('/dashboard')
        ->clickLink('Create Playlist')
        ->on(new CreatePlaylist)
        ->assertSee('@create');

セレクタの簡略記述Shorthand Selectors

ページのelementsメソッドにより、覚えやすいCSSセレクタの短縮形を素早く定義できます。例として、アプリケーションのログインページの"email"入力フィールドの短縮形を定義してみましょう。The elements method of pages allows you to define quick, easy-to-remember shortcuts for any CSS selector on your page. For example, let's define a shortcut for the "email" input field of the application's login page:

/**
 * ページ要素の短縮形を取得
 *
 * @return array
 */
public function elements()
{
    return [
        '@email' => 'input[name=email]',
    ];
}

これで、完全なCSSセレクタを指定する箇所ならどこでも、この短縮セレクタを使用できます。Now, you may use this shorthand selector anywhere you would use a full CSS selector:

$browser->type('@email', 'taylor@laravel.com');

グローバルなセレクタ簡略記述Global Shorthand Selectors

Duskをインストールすると、ベースPageクラスがtests/Browser/Pagesディレクトリへ設置されます。このクラスは、アプリケーション全部のどのページからでも利用可能な、グローバル短縮セレクタを定義するsiteElementsメソッドを含んでいます。After installing Dusk, a base Page class will be placed in your tests/Browser/Pages directory. This class contains a siteElements method which may be used to define global shorthand selectors that should be available on every page throughout your application:

/**
 * サイトのグローバル要素短縮形の取得
 *
 * @return array
 */
public static function siteElements()
{
    return [
        '@element' => '#selector',
    ];
}

ページメソッドPage Methods

ページに対し定義済みのデフォルトメソッドに加え、テスト全体で使用できる追加メソッドも定義できます。たとえば、音楽管理アプリケーションを構築中だと想像してみましょう。アプリケーションのあるページでプレイリストを作成するのは、よくあるアクションです。各テストごとにプレイリスト作成のロジックを書き直す代わりに、ページクラスにcreatePlaylistメソッドを定義することができます。In addition to the default methods defined on pages, you may define additional methods which may be used throughout your tests. For example, let's imagine we are building a music management application. A common action for one page of the application might be to create a playlist. Instead of re-writing the logic to create a playlist in each test, you may define a createPlaylist method on a page class:

<?php

namespace Tests\Browser\Pages;

use Laravel\Dusk\Browser;

class Dashboard extends Page
{
    // 他のページメソッドの定義…

    /**
     * 新しいプレイリストの作成
     *
     * @param  \Laravel\Dusk\Browser  $browser
     * @param  string  $name
     * @return void
     */
    public function createPlaylist(Browser $browser, $name)
    {
        $browser->type('name', $name)
                ->check('share')
                ->press('Create Playlist');
    }
}

メソッドを定義すれば、このページを使用するすべてのテストの中で使用できます。ブラウザインスタンスは自動的にページメソッドへ渡されます。Once the method has been defined, you may use it within any test that utilizes the page. The browser instance will automatically be passed to the page method:

use Tests\Browser\Pages\Dashboard;

$browser->visit(new Dashboard)
        ->createPlaylist('My Playlist')
        ->assertSee('My Playlist');

継続的インテグレーションContinuous Integration

Travis CITravis CI

Travis CI上でDuskテストを実行するためには、Ubuntu 14.04 (Trusty)環境を"sudo-enabled"で使用する必要があります。Travis CIはグラフィカルな環境ではないため、Chromeブラウザを実行するには追加の手順を行う必要があります。さらに、PHPの組み込みWebサーバを起動するために、php artisan serveを使用する必要もあるでしょう。To run your Dusk tests on Travis CI, we will need to use the "sudo-enabled" Ubuntu 14.04 (Trusty) environment. Since Travis CI is not a graphical environment, we will need to take some extra steps in order to launch a Chrome browser. In addition, we will use php artisan serve to launch PHP's built-in web server:

sudo: required
dist: trusty

before_script:
    - export DISPLAY=:99.0
    - sh -e /etc/init.d/xvfb start
    - ./vendor/laravel/dusk/bin/chromedriver-linux &
    - cp .env.testing .env
    - php artisan serve > /dev/null 2>&1 &

script:
    - php artisan dusk

CircleCICircleCI

CircleCI 1.0CircleCI 1.0

CircleCI1.0を使用し、Duskテストを実行する場合、以下の設定ファイルを手始めに利用できます。TravisCIと同様に、php artisan serveコマンドを使用し、PHP組み込みWebサーバを起動できます。If you are using CircleCI 1.0 to run your Dusk tests, you may use this configuration file as a starting point. Like TravisCI, we will use the php artisan serve command to launch PHP's built-in web server:

test:
    pre:
        - "./vendor/laravel/dusk/bin/chromedriver-linux":
            background: true
        - cp .env.testing .env
        - "php artisan serve":
            background: true

    override:
        - php artisan dusk

CircleCI 2.0CircleCI 2.0

DuskテストにCircleCI2.0を使用する場合、ビルドに以下のステップを追加してください。If you are using CircleCI 2.0 to run your Dusk tests, you may add these steps to your build:

 version: 2
 jobs:
     build:
         steps:
              - run:
                  name: Start Chrome Driver
                  command: ./vendor/laravel/dusk/bin/chromedriver-linux
                  background: true
             - run:
                 name: Run Laravel Server
                 command: php artisan serve
                 background: true
             - run:
                 name: Run Laravel Dusk Tests
                 command: php artisan dusk

章選択

公式パッケージ

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作