function UserRolesAssignmentTest::testCreateUserWithRole

Same name in other branches
  1. 9 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 that when creating a user the role can be assigned. And that it can be removed again.

File

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

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->drupalPostForm('admin/people/create', $edit, t('Create new account'));
    $this->assertText(t('Created a new user account for @name.', [
        '@name' => $edit['name'],
    ]));
    // Get the newly added user.
    $account = user_load_by_name($edit['name']);
    $this->drupalGet('user/' . $account->id() . '/edit');
    $this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
    $this->userLoadAndCheckRoleAssigned($account, $rid);
    // Remove the role again.
    $this->drupalPostForm('user/' . $account->id() . '/edit', [
        "roles[{$rid}]" => FALSE,
    ], t('Save'));
    $this->assertText(t('The changes have been saved.'));
    $this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
    $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
}

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