Search code examples
behat

Use random var in behat tests to produce unique usernames


Right now I am creating users using something like the following

Given users:
| name | status | roles |
| kyle | 1 | authenticated user |
| cartman | 1 | admin |

Is there a possibility to add random strings in these names?


Solution

  • If I didn't misunderstand, you can do this instead.

    Gherkin

    Scenario: Create random users
      Given I create "3" users
    

    FeatureContext

    var $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var $status = [0, 1];
    var $roles = ['authenticated user', 'admin', 'superman'];
    
    /**
     * @Given /^I create "([^"]*)" users$/
     */
    public function createDummyUsers($count)
    {
        for ($i = 0; $i < $count; $i++) {
            $name = substr(str_shuffle($this->str), 0, 8);
            $status = $this->status[array_rand($this->status, 1)];
            $role = $this->roles[array_rand($this->roles, 1)];
    
            echo "You've just created $name - $status -$role" . PHP_EOL;
        }
    }
    

    Prints

    You've just created mqBWAQJK - 1 - superman
    You've just created WYuAZSco - 0 - admin
    You've just created HCNWvVth - 1 - admin
    
    You've just created EmLkVRpO - 1 -superman
    You've just created pxWcsuPl - 1 -authenticated user
    You've just created mLYrlKdz - 0 -superman