function BlockTest::testBlockVisibility

Tests block visibility.

File

core/modules/block/tests/src/Functional/BlockTest.php, line 27

Class

BlockTest
Tests basic block functionality.

Namespace

Drupal\Tests\block\Functional

Code

public function testBlockVisibility() {
  $block_name = 'system_powered_by_block';
  // Create a random title for the block.
  $title = $this->randomMachineName(8);
  // Enable a standard block.
  $default_theme = $this->config('system.theme')
    ->get('default');
  $edit = [
    'id' => strtolower($this->randomMachineName(8)),
    'region' => 'sidebar_first',
    'settings[label]' => $title,
    'settings[label_display]' => TRUE,
  ];
  // Set the block to be hidden on any user path, and to be shown only to
  // authenticated users.
  $edit['visibility[request_path][pages]'] = '/user*';
  $edit['visibility[request_path][negate]'] = TRUE;
  $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
  $this->drupalGet('admin/structure/block/add/' . $block_name . '/' . $default_theme);
  $this->assertFieldChecked('edit-visibility-request-path-negate-0');
  $this->drupalPostForm(NULL, $edit, t('Save block'));
  $this->assertText('The block configuration has been saved.', 'Block was saved');
  $this->clickLink('Configure');
  $this->assertFieldChecked('edit-visibility-request-path-negate-1');
  $this->drupalGet('');
  $this->assertText($title, 'Block was displayed on the front page.');
  $this->drupalGet('user');
  $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
  // Confirm that the block is not displayed to anonymous users.
  $this->drupalLogout();
  $this->drupalGet('');
  $this->assertNoText($title, 'Block was not displayed to anonymous users.');
  // Confirm that an empty block is not displayed.
  $this->assertNoText('Powered by Drupal', 'Empty block not displayed.');
  $this->assertNoRaw('sidebar-first', 'Empty sidebar-first region is not displayed.');
}

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