Search code examples
phpstringrandomparametersbehat

Random String passed as the same string php


Trying to create a functional test using PHP with Behat and I want a random string for an email, but I want the string to be random every time a new test runs, but I want to pass the same string created to different tests as a parameter.

So if I generate a 10 digit string, I would like to generate the string and then pass it though other tests as the same 10 digit sequence

I'm new to PHP so I'm not exactly positive how to set it up, but here's what I have so far in my Behat context file

class FeatureContext implements Context {

private $MailPage;
private $registrationpage;


/**
 * Initializes context.
 *
 * Every scenario gets its own context instance.
 * You can also pass arbitrary arguments to the
 * context constructor through behat.yml.
 */
public function __construct(MailPage $mailPage, RegistrationPage $registrationpage)
{
    // Page obects injected directly in constructor with type hints.
    $this->MailPage = $MailPage;
    $this->registrationpage = $registrationpage;
}

/**
 * @BeforeSuite
 */
public static function  generateRandomString() {

    // Generate random string for Email implementation.
    $randomString = bin2hex(openssl_random_pseudo_bytes(10));
    return $randomString;

}


/**
 * @Given /^I register a temporary email address $/
 */
public function iRegisterATemporaryEmailAddress()
{
    $this->MailPage->grabNewEmail(self::generateRandomEmail());
}

/**
 * @Given /^I register a Developer account$/
 */
public function iRegisterADeveloperAccount()
{

    $this->registrationpage->fillInFormDetails(self::generateRandomEmail());
}

The Problem I run into is that with the parameter as it is, It generates a different string every time it's called, but I only want it to generate it once for the entire suite. Any ideas?


Solution

  • 1- Call your method from the constructor.

    2- Save the generated value in a variable using this

    private $randomString ;
    public function __construct(MailPage $mailPage, RegistrationPage $registrationpage)
    {
       //your code
       $this->randomString = $this->generateRandomString();
    
    }
    

    3- To use this variable you can call it inside your class methods like this $this->randomString.

    Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.