Using Faker and ENV vars with Behat
UPDATED April 01 2015
Realized I needed more “tokens” and I was already using my .env file for info for Seeding and for our different servers. So the Trait now pulls those in.
This is a simple trait to use in your FeatureContext file to then get the power of Faker in your Behat tests
The Trait <?php
trait TokenFaker {
public function checkForTokens($arg)
{
$arg = str_replace($this->replaceAbleTokens(), $this->loadTokensValues(), $arg);
return $arg;
}
protected function replaceAbleTokens()
{
return array_merge($this->getManualTokensKeys(), $this->getEnvTokensKeys());
}
protected function getManualTokensKeys()
{
return [
'TOKEN_EMAIL',
'TOKEN_UUID',
'TOKEN_USERNAME',
'TOKEN_URL'];
}
protected function loadTokensValues()
{
return array_merge($this->getManualTokenValues(), $this->getEnvTokensValues());
}
protected function getManualTokenValues()
{
return [
$this->faker->email,
$this->faker->uuid,
$this->faker->word,
$this->faker->url
];
}
protected function getEnvTokensValues()
{
return array_values($_ENV);
}
protected function getEnvTokensKeys()
{
return array_keys($_ENV);
}
}
The Feature Context In my Feature Context I setup Faker and instantiate it and use the trait