Array as argument in Behat step
Asked Answered
I

2

5

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.

Imogeneimojean answered 14/11, 2014 at 10:7 Comment(0)
A
7

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);
}
Allethrin answered 19/11, 2015 at 1:32 Comment(0)
I
2

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) {
      // ...
    }
  }
Imogeneimojean answered 14/11, 2014 at 10:10 Comment(1)
Would you mind sharing what your step definition and context method looks like for this?Allethrin

© 2022 - 2024 — McMap. All rights reserved.