rotty_dean
(Dean Sanderson)
February 4, 2016, 7:24pm
1
I am new to using the test features of Yii 2. I have managed to get a simple login test all working with the examples. But i want to create more tests in my admin section. This requires the user to login for every function. How would i reuse the login code every time instead of writing login actions on every test?
jacmoe
(Jacob Moen)
February 6, 2016, 8:38am
2
Yes, that is possible.
Take a look at the code that the advanced app template generates for you and find ‘tests/codeception/common/_pages’.
The login page:
<?php
namespace tests\codeception\common\_pages;
use yii\codeception\BasePage;
/**
* Represents loging page
* @property \codeception_frontend\AcceptanceTester|\codeception_frontend\FunctionalTester|\codeception_backend\AcceptanceTester|\codeception_backend\FunctionalTester $actor
*/
class LoginPage extends BasePage
{
public $route = 'user/login';
/**
* @param string $username
* @param string $password
*/
public function login($username, $password)
{
$this->actor->fillField('input[name="LoginForm[username]"]', $username);
$this->actor->fillField('input[name="LoginForm[password]"]', $password);
$this->actor->click('login-button');
}
}
Then that one is used in the tests/codeception/frontend/acceptance/LoginCept.php :
<?php
use tests\codeception\frontend\AcceptanceTester;
use tests\codeception\common\_pages\LoginPage;
/* @var $scenario Codeception\Scenario */
$I = new AcceptanceTester($scenario);
$I->wantTo('ensure login page works');
$loginPage = LoginPage::openBy($I);
$I->amGoingTo('submit login form with no data');
$loginPage->login('', '');
$I->expectTo('see validations errors');
$I->see('Username cannot be blank.', '.help-block');
$I->see('Password cannot be blank.', '.help-block');
$I->amGoingTo('try to login with wrong credentials');
$I->expectTo('see validations errors');
$loginPage->login('admin', 'wrong');
$I->expectTo('see validations errors');
$I->see('Incorrect username or password.', '.help-block');
$I->amGoingTo('try to login with correct credentials');
$loginPage->login('erau', 'password_0');
$I->expectTo('see that user is logged');
$I->see('Logout (erau)', 'form button[type=submit]');
$I->dontSeeLink('Login');
$I->dontSeeLink('Signup');
/** Uncomment if using WebDriver
* $I->click('Logout (erau)');
* $I->dontSeeLink('Logout (erau)');
* $I->seeLink('Login');
*/