You are here

protected function UniqueFieldValidationRuleTest::setUp in Field Validation 8

Overrides FieldValidationRuleBase::setUp

File

tests/src/Kernel/Plugin/FieldValidationRule/UniqueFieldValidationRuleTest.php, line 66

Class

UniqueFieldValidationRuleTest
Tests UniqueFieldValidationRule.

Namespace

Drupal\Tests\field_validation\Kernel\Plugin\FieldValidationRule

Code

protected function setUp() {
  parent::setUp();
  $this
    ->setupTestArticle(self::FIELD_NAME);
  NodeType::create([
    'type' => 'page',
    'label' => 'Basic page',
  ])
    ->save();
  FieldConfig::create([
    'entity_type' => 'node',
    'field_name' => self::FIELD_NAME,
    'bundle' => 'page',
  ])
    ->save();
  $this->ruleSet = $this->ruleSetStorage
    ->create([
    'name' => 'unique_field_test',
    'entity_type' => 'node',
    'bundle' => 'article',
  ]);
  $this->ruleSet
    ->addFieldValidationRule([
    'id' => self::RULE_ID,
    'title' => self::RULE_TITLE,
    'weight' => 1,
    'field_name' => self::FIELD_NAME,
    'column' => 'value',
    'error_message' => 'Text is not unique in scope!',
    'data' => [
      'scope' => 'bundle',
    ],
  ]);
  $this->ruleSet
    ->save();

  // Test entity which test is trying to update.
  $this->entity = $this->nodeStorage
    ->create([
    'type' => 'article',
    'title' => 'test',
    self::FIELD_NAME => '',
  ]);

  // Comparison entity for bundle scope.
  $this->entitySameBundle = $this->nodeStorage
    ->create([
    'type' => 'article',
    'title' => 'unique 2',
    self::FIELD_NAME => '1337',
  ]);
  $this->entitySameBundle
    ->save();

  // Comparison entity for entity scope.
  $this->entityOtherBundle = $this->nodeStorage
    ->create([
    'type' => 'page',
    'title' => 'unique 2',
    self::FIELD_NAME => '1337',
  ]);
  $this->entityOtherBundle
    ->save();
  $this->entity
    ->get(self::FIELD_NAME)
    ->getFieldDefinition()
    ->addConstraint('FieldValidationConstraint', [
    'ruleset_name' => $this->ruleSet
      ->getName(),
  ]);
}