| layout | doc |
|---|---|
| title | Laravel - Codeception - Documentation |
{% highlight yaml %} composer require --dev codeception/module-laravel
{% endhighlight %}
This module allows you to run functional tests for Laravel 6.0+ It should not be used for acceptance tests. See the Acceptance tests section below for more details.
https://github.com/Codeception/laravel-module-tests
- cleanup:
boolean, defaulttrue- all database queries will be run in a transaction, which will be rolled back at the end of each test. - run_database_migrations:
boolean, defaultfalse- run database migrations before each test. - database_migrations_path:
string, defaultnull- path to the database migrations, relative to the root of the application. - run_database_seeder:
boolean, defaultfalse- run database seeder before each test. - database_seeder_class:
string, default `` - database seeder class name. - environment_file:
string, default.env- the environment file to load for the tests. - bootstrap:
string, defaultbootstrap/app.php- relative path to app.php config file. - root:
string, default `` - root path of the application. - packages:
string, defaultworkbench- root path of application packages (if any). - vendor_dir:
string, defaultvendor- optional relative path to vendor directory. - disable_exception_handling:
boolean, defaulttrue- disable Laravel exception handling. - disable_middleware:
boolean, defaultfalse- disable all middleware. - disable_events:
boolean, defaultfalse- disable events (does not disable model events). - disable_model_events:
boolean, defaultfalse- disable model events. - url:
string, default `` - the application URL. - headers:
array<string, string>- default headers are set before each test.
Enabling module:
{% highlight yaml %} yml modules: enabled: - Laravel
{% endhighlight %}
Enabling module with custom .env file
{% highlight yaml %} yml modules: enabled: - Laravel: environment_file: .env.testing
{% endhighlight %}
- app -
Illuminate\Foundation\Application - config -
array
ORM: Only include the database methods of this module:- dontSeeRecord
- grabNumRecords
- grabRecord
- have
- haveMultiple
- haveRecord
- make
- makeMultiple
- seedDatabase
- seeNumRecords
- seeRecord
See WebDriver module for general information on how to load parts of a framework module.
You should not use this module for acceptance tests. If you want to use Eloquent within your acceptance tests (paired with WebDriver) enable only ORM part of this module:
{% highlight yaml %}
modules: enabled: - WebDriver: browser: chrome url: http://127.0.0.1:8000 - Laravel: part: ORM environment_file: .env.testing
{% endhighlight %}
hidden API method, expected to be used from Helper classes
apiparam mixed$locatorreturn iterable
Locates element using available Codeception locator types:
- XPath
- CSS
- Strict Locator
Use it in Helpers or GroupObject or Extension classes:
{% highlight php %}
getModule('Laravel')->_findElements('.items'); $els = $this->getModule('Laravel')->_findElements(['name' => 'username']); $editLinks = $this->getModule('Laravel')->_findElements(['link' => 'Edit']); // now you can iterate over $editLinks and check that all them have valid hrefs {% endhighlight %} WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances #### _getResponseContent *hidden API method, expected to be used from Helper classes* * `api` * `throws ModuleException` * `return string` Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module. {% highlight php %} assertStringContainsString($text, $this->getModule('Laravel')->_getResponseContent(), "response contains"); } {% endhighlight %} #### _loadPage *hidden API method, expected to be used from Helper classes* * `api` * `param string` $method * `param string` $uri * `param array` $parameters * `param array` $files * `param array` $server * `param ?string` $content * `return void` Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step. {% highlight php %} getModule('Laravel')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]); } {% endhighlight %} #### _request *hidden API method, expected to be used from Helper classes* * `api` * `see` `_loadPage` * `param string` $method * `param string` $uri * `param array` $parameters * `param array` $files * `param array` $server * `param ?string` $content * `throws ExternalUrlException|ModuleException` * `return ?string` Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body. {% highlight php %} getModule('Laravel')->_request('POST', '/api/v1/users', ['name' => $name]); $user = json_decode($userData); return $user->id; } {% endhighlight %} Does not load the response into the module so you can't interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method. #### _savePageSource *hidden API method, expected to be used from Helper classes* * `api` * `param string` $filename * `return void` Saves page source of to a file {% highlight php %} $this->getModule('Laravel')->_savePageSource(codecept_output_dir().'page.html'); {% endhighlight %} #### amActingAs * `param \Illuminate\Contracts\Auth\Authenticatable` $user * `param ?string` $guardName * `return void` Set the given user object to the current or specified Guard. {% highlight php %} amActingAs($user); {% endhighlight %} #### amHttpAuthenticated * `param string` $username * `param string` $password * `return void` Authenticates user for HTTP_AUTH #### amLoggedAs * `param Authenticatable|array` $user * `param string|null` $guardName * `return void` Set the currently logged in user for the application. Unlike 'amActingAs', this method does update the session, fire the login events and remember the user as it assigns the corresponding Cookie. {% highlight php %} amLoggedAs(['username' => 'jane@example.com', 'password' => 'password']); // provide User object that implements the User interface $I->amLoggedAs( new User ); // can be verified with $I->seeAuthentication(); {% endhighlight %} #### amOnAction * `param string` $action * `param mixed` $parameters * `return void` Opens web page by action name {% highlight php %} amOnAction('PostsController@index'); // Laravel 8+: $I->amOnAction(PostsController::class . '@index'); {% endhighlight %} #### amOnPage * `param string` $page * `return void` Opens the page for the given relative URI. {% highlight php %} amOnPage('/'); // opens /register page $I->amOnPage('/register'); {% endhighlight %} #### amOnRoute * `param string` $routeName * `param mixed` $params * `return void` Opens web page using route name and parameters. {% highlight php %} amOnRoute('posts.create'); {% endhighlight %} #### assertAuthenticatedAs * `param \Illuminate\Contracts\Auth\Authenticatable` $user * `param ?string` $guardName * `return void` Assert that the user is authenticated as the given user. {% highlight php %} assertAuthenticatedAs($user); {% endhighlight %} #### assertCredentials * `param array` $credentials * `param ?string` $guardName * `return void` Assert that the given credentials are valid. {% highlight php %} assertCredentials([ 'email' => 'john_doe@gmail.com', 'password' => '123456' ]); {% endhighlight %} #### assertInvalidCredentials * `param array` $credentials * `param ?string` $guardName * `return void` Assert that the given credentials are invalid. {% highlight php %} assertInvalidCredentials([ 'email' => 'john_doe@gmail.com', 'password' => 'wrong_password' ]); {% endhighlight %} #### attachFile * `param ` $field * `param string` $filename * `return void` Attaches a file relative to the Codeception `_data` directory to the given file upload field. {% highlight php %} attachFile('input[@type="file"]', 'prices.xls'); {% endhighlight %} #### callArtisan * `param string` $command * `param array` $parameters * `param ?\Symfony\Component\Console\Output\OutputInterface` $output * `return string|void` Call an Artisan command. {% highlight php %} callArtisan('command:name'); $I->callArtisan('command:name', ['parameter' => 'value']); {% endhighlight %} Use 3rd parameter to pass in custom `OutputInterface` #### checkOption * `param ` $option * `return void` Ticks a checkbox. For radio buttons, use the `selectOption` method instead. {% highlight php %} checkOption('#agree'); {% endhighlight %} #### clearApplicationHandlers * `return void` Clear the registered application handlers. {% highlight php %} clearApplicationHandlers(); {% endhighlight %} #### click * `param string|array` $link * `param ` $context * `return void` Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched. For images, the "alt" attribute and inner text of any parent links are searched. The second parameter is a context (CSS or XPath locator) to narrow the search. Note that if the locator matches a button of type `submit`, the form will be submitted. {% highlight php %} click('Logout'); // button of form $I->click('Submit'); // CSS button $I->click('#form input[type=submit]'); // XPath $I->click('//form/*[@type="submit"]'); // link in context $I->click('Logout', '#nav'); // using strict locator $I->click(['link' => 'Login']); {% endhighlight %} #### deleteHeader @deprecated * `param string` $name * `return void` #### disableEvents * `return void` Disable events for the next requests. This method does not disable model events. To disable model events you have to use the disableModelEvents() method. {% highlight php %} disableEvents(); {% endhighlight %} #### disableExceptionHandling * `return void` Disable Laravel exception handling. {% highlight php %} disableExceptionHandling(); {% endhighlight %} #### disableMiddleware * `param string|array|null` $middleware * `return void` Disable middleware for the next requests. {% highlight php %} disableMiddleware(); {% endhighlight %} #### disableModelEvents * `return void` Disable model events for the next requests. {% highlight php %} disableModelEvents(); {% endhighlight %} #### dontSee * `param string` $text * `param array|string` $selector optional * `return void` Checks that the current page doesn't contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region. {% highlight php %} dontSee('Login'); // I can suppose user is already logged in $I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page $I->dontSee('Sign Up','//body/h1'); // with XPath $I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator {% endhighlight %} Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like: - `I am Stronger than thou
` - `<script>document.createElement('strong');</script>` But will ignore strings like: - `Home` - `I am Stronger than thou
` - `<script>document.createElement('strong');</script>` But will *not* be true for strings like: - `Home` - `Password:
Do you agree to our terms?
Subscribe to our newsletter?
Select pricing plan: Free Paid {% endhighlight %} You could write the following to submit it: {% highlight php %} submitForm( '#userForm', [ 'user' => [ 'login' => 'Davert', 'password' => '123456', 'agree' => true ] ], 'submitButton' ); {% endhighlight %} Note that "2" will be the submitted value for the "plan" field, as it is the selected option. To uncheck the pre-checked checkbox "newsletter", call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the "newsletter" field in the `$params` array). You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm. {% highlight php %} submitForm( '#userForm', [ 'user' => [ 'login' => 'Davert', 'password' => '123456', 'agree' => true ] ] ); {% endhighlight %} This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic. {% highlight php %} 'value', 'field2' => 'another value', 'checkbox1' => true, // ... ]; $I->submitForm('#my-form', $form, 'submitButton'); // $I->amOnPage('/path/to/form-page') may be needed $I->seeInFormFields('#my-form', $form); {% endhighlight %} Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox's value in the DOM. {% highlight php %} submitForm('#my-form', [ 'field1' => 'value', 'checkbox' => [ 'value of first checkbox', 'value of second checkbox', ], 'otherCheckboxes' => [ true, false, false ], 'multiselect' => [ 'first option value', 'second option value' ] ]); {% endhighlight %} Mixing string and boolean values for a checkbox's value is not supported and may produce unexpected results. Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider: {% highlight php %} submitForm('#my-form', [ 'field[]' => 'value', 'field[]' => 'another value', // 'field[]' is already a defined key ]); {% endhighlight %} The solution is to pass an array value: {% highlight php %} submitForm('#my-form', [ 'field' => [ 'value', 'another value', ] ]); {% endhighlight %} #### switchToIframe * `param string` $name * `return void` Switch to iframe or frame on the page. Example: {% highlight html %} <iframe name="another_frame" src="http://example.com"> {% endhighlight %} {% highlight php %} switchToIframe("another_frame"); {% endhighlight %} #### uncheckOption * `param ` $option * `return void` Unticks a checkbox. {% highlight php %} uncheckOption('#notify'); {% endhighlight %} #### unsetHttpHeader * `param string` $name the name of the header to unset. * `return void` Unsets a HTTP header (that was originally added by [haveHttpHeader()](#haveHttpHeader)), so that subsequent requests will not send it anymore. Example: {% highlight php %} haveHttpHeader('X-Requested-With', 'Codeception'); $I->amOnPage('test-headers.php'); // ... $I->unsetHeader('X-Requested-With'); $I->amOnPage('some-other-page.php'); {% endhighlight %}