phpfunctional-testingcodeception

Loop through multiple accounts in codeception functional test


I got multiple accounts: "userWithCertainRole", "userWithAnotherRole" & "userWithTwoRoles". I want to functional test a specific page for all these accounts with certain roles. The functional test is the same for all the accounts, so I don't want to duplicate the code or make multiple php files. Is there any way to loop through those three accounts in one functional test?

/**
 * @var string|null
 */
protected ?string $account = 'userWithCertainRole';

/**
 * @param FunctionalTester $I
 */
public function page(FunctionalTester $I)
{
    $this->login($I);
    $I->amOnPage('/page');
    $I->dontSee('You cannot access this page with this role');
    $I->see('Page header');
}

Solution

  • Use data provider as in PHPUnit, or Codeception specific Example anotation/attribute for providing data to test method.

    See https://codeception.com/docs/AdvancedUsage#Examples-Attribute

    /**
     * @dataProvider getRoles
     */
    public function page(FunctionalTester $I, Example $example)
    {
        $this->login($example['username'], $example['password']);
    }
    
    protected function getRoles(): array
    {
      // keys make test output easier to understand
      return [
        'userWithRole1' => ['username' => 'username1', 'password' => 'password1'],
        'userWithRole2' => ['username' => 'username2', 'password' => 'password2'],
        'userWithRole3' => ['username' => 'username3', 'password' => 'password3'],
      ];
    }