You are here

public function RoleAssignTest::testRoleAssignRolesForm in Role Delegation 8

Test that we can assign roles we have access to via the Roles form.

File

tests/src/Functional/RoleAssignTest.php, line 84

Class

RoleAssignTest
Functional tests for assigning roles.

Namespace

Drupal\Tests\role_delegation\Functional

Code

public function testRoleAssignRolesForm() {
  $user_storage = \Drupal::entityTypeManager()
    ->getStorage('user');

  // Create a role and login as a user with the permission to assign it.
  $rid1 = $this
    ->drupalCreateRole([]);
  $rid2 = $this
    ->drupalCreateRole([]);
  $current_user = $this
    ->drupalCreateUser([
    sprintf('assign %s role', $rid1),
    sprintf('assign %s role', $rid2),
  ]);
  $this
    ->drupalLogin($current_user);

  // Go to the users roles edit page.
  $account = $this
    ->drupalCreateUser();
  $this
    ->drupalGet(sprintf('/user/%s/roles', $account
    ->id()));

  // The form element field id and name.
  $field_id = sprintf('edit-role-change-%s', $rid1);
  $field_name = sprintf('role_change[%s]', $rid1);

  // Ensure its disabled by default.
  $this
    ->assertSession()
    ->checkboxNotChecked($field_id);
  self::assertFalse($account
    ->hasPermission('assign $rid1 role'), 'The target user does not have the role by default.');
  $this
    ->assertSession()
    ->checkboxNotChecked($field_id);

  // Assign the role and ensure its now checked and assigned.
  $this
    ->submitForm([
    $field_name => $rid1,
  ], 'Save');
  $user_storage
    ->resetCache();
  $account = $user_storage
    ->load($account
    ->id());
  self::assertTrue($account
    ->hasRole($rid1), 'The target user has been granted the role.');
  $this
    ->assertSession()
    ->checkboxChecked($field_id);

  // Revoke the role.
  $this
    ->submitForm([
    $field_name => FALSE,
  ], 'Save');
  $user_storage
    ->resetCache();
  $account = $user_storage
    ->load($account
    ->id());
  self::assertFalse($account
    ->hasRole($rid1), 'The target user has gotten the role revoked.');
  $this
    ->assertSession()
    ->checkboxNotChecked($field_id);
}