public function EntityReferenceAutoCreateTest::testAutoCreate

Assert creation on a new entity.

File

drupal/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutoCreateTest.php, line 81
Contains \Drupal\entity_reference\Tests\EntityReferenceAutoCreateTest.

Class

EntityReferenceAutoCreateTest
Tests the Entity Reference auto-creation feature.

Namespace

Drupal\entity_reference\Tests

Code

public function testAutoCreate() {
  $user1 = $this
    ->drupalCreateUser(array(
    'access content',
    "create {$this->referencing_type} content",
  ));
  $this
    ->drupalLogin($user1);
  $new_title = $this
    ->randomName();

  // Assert referenced node does not exist.
  $base_query = \Drupal::entityQuery('node');
  $base_query
    ->condition('type', $this->referenced_type)
    ->condition('title', $new_title);
  $query = clone $base_query;
  $result = $query
    ->execute();
  $this
    ->assertFalse($result, 'Referenced node does not exist yet.');
  $edit = array(
    'title' => $this
      ->randomName(),
    'test_field[und][0][target_id]' => $new_title,
  );
  $this
    ->drupalPost("node/add/{$this->referencing_type}", $edit, 'Save');

  // Assert referenced node was created.
  $query = clone $base_query;
  $result = $query
    ->execute();
  $this
    ->assertTrue($result, 'Referenced node was created.');
  $referenced_nid = key($result);

  // Assert the referenced node is associated with referencing node.
  $result = \Drupal::entityQuery('node')
    ->condition('type', $this->referencing_type)
    ->execute();
  $referencing_nid = key($result);
  $referencing_node = node_load($referencing_nid);
  $this
    ->assertEqual($referenced_nid, $referencing_node->test_field[Language::LANGCODE_NOT_SPECIFIED][0]['target_id'], 'Newly created node is referenced from the referencing node.');
}