function UserRolesAssignmentTest::testCreateUserWithRole

Same name and namespace in other branches
  1. 8.9.x core/modules/user/tests/src/Functional/UserRolesAssignmentTest.php \Drupal\Tests\user\Functional\UserRolesAssignmentTest::testCreateUserWithRole()
  2. 10 core/modules/user/tests/src/Functional/UserRolesAssignmentTest.php \Drupal\Tests\user\Functional\UserRolesAssignmentTest::testCreateUserWithRole()
  3. 11.x core/modules/user/tests/src/Functional/UserRolesAssignmentTest.php \Drupal\Tests\user\Functional\UserRolesAssignmentTest::testCreateUserWithRole()

Tests assigning a role at user creation and removing the role.

File

core/modules/user/tests/src/Functional/UserRolesAssignmentTest.php, line 56

Class

UserRolesAssignmentTest
Tests that users can be assigned and unassigned roles.

Namespace

Drupal\Tests\user\Functional

Code

public function testCreateUserWithRole() {
    $rid = $this->drupalCreateRole([
        'administer users',
    ]);
    // Create a new user and add the role at the same time.
    $edit = [
        'name' => $this->randomMachineName(),
        'mail' => $this->randomMachineName() . '@example.com',
        'pass[pass1]' => $pass = $this->randomString(),
        'pass[pass2]' => $pass,
        "roles[{$rid}]" => $rid,
    ];
    $this->drupalGet('admin/people/create');
    $this->submitForm($edit, 'Create new account');
    $this->assertSession()
        ->pageTextContains('Created a new user account for ' . $edit['name'] . '.');
    // Get the newly added user.
    $account = user_load_by_name($edit['name']);
    $this->drupalGet('user/' . $account->id() . '/edit');
    $this->assertSession()
        ->checkboxChecked('edit-roles-' . $rid);
    $this->userLoadAndCheckRoleAssigned($account, $rid);
    // Remove the role again.
    $this->drupalGet('user/' . $account->id() . '/edit');
    $this->submitForm([
        "roles[{$rid}]" => FALSE,
    ], 'Save');
    $this->assertSession()
        ->pageTextContains('The changes have been saved.');
    $this->assertSession()
        ->checkboxNotChecked('edit-roles-' . $rid);
    $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.