function ConfigureAndExecuteTest::testUpcastInCondition

Tests upcasting in a condition.

File

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

Class

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

Namespace

Drupal\Tests\rules\Functional

Code

public function testUpcastInCondition() {
    
    /** @var \Drupal\Tests\WebAssert $assert */
    $assert = $this->assertSession();
    // Create a rule.
    $rule = $this->expressionManager
        ->createRule();
    // Add a condition to check if the user has the 'test-editor' role.
    $rule->addCondition('rules_user_has_role', ContextConfig::create()->map('user', '@user.current_user_context:current_user')
        ->setValue('roles', [
        'test-editor',
    ]));
    // Add an action to display a system message.
    $message = '-- RULE to test upcasting in condition --';
    $rule->addAction('rules_system_message', ContextConfig::create()->setValue('message', $message)
        ->setValue('type', 'status'));
    // Set the even to User Login and save the configuration.
    $expr_id = 'test_upcast';
    $config_entity = $this->storage
        ->create([
        'id' => $expr_id,
        'expression' => $rule->getConfiguration(),
        'events' => [
            [
                'event_name' => 'rules_user_login',
            ],
        ],
    ]);
    $config_entity->save();
    // Log in and check that the rule is triggered.
    $this->drupalLogin($this->account);
    $assert->pageTextNotContains($message);
    // Add the required role to the user.
    $this->account
        ->addRole('test-editor');
    $this->account
        ->save();
    // Log out and in and check that the rule is triggered.
    $this->drupalLogout();
    $this->drupalLogin($this->account);
    $assert->pageTextContains($message);
    // Remove the role from the user.
    $this->account
        ->removeRole('test-editor');
    $this->account
        ->save();
    // Log out and in and check that the rule is not triggered.
    $this->drupalLogout();
    $this->drupalLogin($this->account);
    $assert->pageTextNotContains($message);
}