You are here

public function ExampleFunctionalTest::testNewPage in Examples for Developers 3.x

Same name and namespace in other branches
  1. 8 testing_example/tests/src/Functional/ExampleFunctionalTest.php \Drupal\Tests\testing_example\Functional\ExampleFunctionalTest::testNewPage()

Demonstrate node creation through UI interaction.

File

modules/testing_example/tests/src/Functional/ExampleFunctionalTest.php, line 75

Class

ExampleFunctionalTest
Class ExampleFunctionalTest.

Namespace

Drupal\Tests\testing_example\Functional

Code

public function testNewPage() {

  // We log in an administrator because they will have permissions to create
  // content.
  $this
    ->drupalLogin($this->adminUser);

  // For many assertions, we need a WebAssert object. This object gives us
  // assertion types for the HTTP requests we make, such as content and the
  // HTTP status code.

  /** @var \Drupal\Tests\WebAssert $assert */
  $assert = $this
    ->assertSession();

  // Get the page that lets us add new content.
  $this
    ->drupalGet('node/add/test_content_type');

  // Use the WebAssert object to assert the HTTP status code.
  $assert
    ->statusCodeEquals(200);

  // Set up our new piece of content.
  $nodeTitle = 'Test node for testNewPage';
  $edit = [
    'title[0][value]' => $nodeTitle,
    'body[0][value]' => 'Body of test node',
  ];

  // Tell Drupal to post our new content. We post to NULL for the URL which
  // tells drupalPostForm() to use the current page.
  $this
    ->drupalPostForm(NULL, $edit, 'op');

  // Check our expectations.
  $assert
    ->statusCodeEquals(200);
  $assert
    ->linkExists($nodeTitle);

  // Log in our non-admin user and navigate to the node.
  $this
    ->drupalLogin($this->authUser);

  // We can search for the node by its title. Since the node object can also
  // tell us its URL, we can just feed that information into drupalGet().

  /** @var \Drupal\node\NodeInterface $createdNode */
  $createdNode = $this
    ->drupalGetNodeByTitle($nodeTitle);
  $url = $createdNode
    ->toUrl();
  $this
    ->drupalGet($url);
  $assert
    ->statusCodeEquals(200);

  // Look at the page title.
  $assert
    ->titleEquals("{$nodeTitle} | Drupal");

  // Find the title of the node itself.
  $nodeTitleElement = $this
    ->getSession()
    ->getPage()
    ->find('css', 'h1 span');
  $this
    ->assertEquals($nodeTitleElement
    ->getText(), $nodeTitle);
}