function ConfigureAndExecuteTest::testUpcastInAction

Tests upcasting in an action.

File

tests/src/Functional/ConfigureAndExecuteTest.php, line 631

Class

ConfigureAndExecuteTest
Tests that a rule can be configured and triggered when a node is edited.

Namespace

Drupal\Tests\rules\Functional

Code

public function testUpcastInAction() {
    // Log in.
    $this->drupalLogin($this->account);
    // Create a rule.
    $rule = $this->expressionManager
        ->createRule();
    // Add an action to add 'Editor' role to the current user. The role value
    // here is just the machine name as text, and will be upcast to the full
    // role object when the rule is triggered.
    $rule->addAction('rules_user_role_add', ContextConfig::create()->map('user', '@user.current_user_context:current_user')
        ->setValue('roles', [
        'test-editor',
    ]));
    // Save the configuration.
    $expr_id = 'test_upcast';
    $config_entity = $this->storage
        ->create([
        'id' => $expr_id,
        'expression' => $rule->getConfiguration(),
        'events' => [
            [
                'event_name' => 'rules_entity_insert:node',
            ],
        ],
    ]);
    $config_entity->save();
    // Check that the user does not have the 'test-editor' role.
    $this->assertEmpty(array_intersect([
        'test-editor',
    ], $this->account
        ->getRoles()));
    // Create an article, which will trigger the rule, and add the role.
    $this->drupalCreateNode([
        'type' => 'article',
        'title' => 'Upcasting role in action',
    ]);
    // Reload the user account.
    $account = User::load($this->account
        ->id());
    // Check that the role has been added to the user.
    $this->assertNotEmpty(array_intersect([
        'test-editor',
    ], $account->getRoles()));
}