drupalextension icon indicating copy to clipboard operation
drupalextension copied to clipboard

Is it possible to pass variables in Behat feature files? Variable whose value we do not know

Open sswarupa2017 opened this issue 7 years ago • 1 comments

I am looking to pass the node id as a variable in Behat feature file. The node id will change based on which article is most recent. I need to edit the most recent article, find the node id and compare with the node id from REST API endpoint.

I am using REST context from Behatch and I do not see a way to pass variable's value (dynamic nodeid) from feature file.

I am not sure if I need to reimplement the REST context to be able to pass dynamic value of nodeid in feature file?

Pl. let me know as this is limiting our ability to use Behat where there is need to pass dynamic varable values in Behat feature files, especially when I want to use Out of the box Step defs from Behatch contexts.

I am aware of Scenario Outlines and how to pass variables from feature files, by using Examples. I am looking for passing variables whose values keep changing.

sswarupa2017 avatar Jan 22 '18 16:01 sswarupa2017

@sswarupa2017 look into implementing this using transforms:

Example feature:

Scenario: Example Scenario
  Given the following content:
    """
    title: Example Node
    type: article
    status: 1
    langcode: en
    moderation_state: published
    body: Lorem ipsim
   """
  And I send a "POST" request to "/foobar/[node:recent:id]"

Context source:

/**
 * Transform tokens.
 *
 * @Transform /^(.*\[.*\].*)$/
 */
public function tokenReplace(string $string): string {
  preg_match_all('/\[([^:]*)\:([^\]]*)\]/', $string, $matches);

  for ($i = 0; $i < count($matches[0]); $i++) {
    $token = $matches[1][$i];
    $token_parts = explode(':', $matches[2][$i]);

    $token_text = '';
    switch ($token) {
      case 'node':
        if ($token_parts[0] === 'latest' && $token_parts[1] === 'id') {
          // Lookup node
          // $node = ...
          $token_text = $node->id();
        }
        break;
    }

    if (!empty($token_text)) {
      $string = str_replace($matches[0][$i], $token_text, $string);
    }
  }

  return $string;
}

jacks0n avatar Sep 30 '20 14:09 jacks0n