You are here

public function UserRolesAssignmentTest::testCreateUserWithRole in Drupal 9

Same name and namespace in other branches
  1. 8 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 55

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);
}