Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as argument in Behat step

Tags:

arrays

behat

Is it possible to pass an array as argument in Behat step?

For example want something like this:

When I select <"Alex","Sergey"> in "users"

I know that for this situation I can use:

When I select "Alex" from "users"
And I additionally select "Sergey" from "users"

But the question is about using arrays here.

like image 535
milkovsky Avatar asked Feb 11 '23 13:02

milkovsky


2 Answers

This is what I came up with

Given "foo" translations equal "[foo,bar,bazz]"

/**
 * @Transform /^\[(.*)\]$/
 */
public function castStringToArray($string)
{
    return explode(',', $string);
}

/**
 * @Given /^"([^"]*)" translations equal "([^"]*)"$/
 */
public function translationsEqual($phraseName, $translations)
{
    // we have an array now
    var_dump($translations);
}
like image 68
Brian Litzinger Avatar answered Feb 14 '23 02:02

Brian Litzinger


Option 1

It's possible to make step argument transformations. Then you can easily convert comma-separated string to an array. An Example:

Behat step

Given article "Test article" is published at "Foo, Bar"

Step code:

<?php

use Behat\Behat\Context\BehatContext;

class FeatureContext extends BehatContext
{
    /**
     * @Transform "([^"]*)"
     */
    public function castStringToNumber($value)
    {
        return explode(',' $value);
    }

    /**
     * @Given /^article "([^"]*)" is published at "([^"]*)"$/
     */
    public function givenArticleIsPublishedAtPages($title, $pages){
      foreach ($pages as $page) {
      // ...
    }
  }

Option 2

Another option is to explode a comma-separated string:

Behat step

Given article "Test article" is published at "Foo, Bar"

Step code:

  /**
   * @Given /^article "([^"]*)" is published at "([^"]*)"$/
   */
  public function givenArticleIsPublishedAtMediums($title, $mediums){
    // Explode mediums from a string.
    foreach (explode(',', $mediums) as $medium) {
      // ...
    }
  }
like image 28
milkovsky Avatar answered Feb 14 '23 03:02

milkovsky