Using Faker and ENV vars with Behat

Posted: 2015-03-27 17:33:19

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

<?php

use Faker\Factory as Faker;

class BaseContext extends MinkContext {
     use TokenFaker;


    public function __construct($parameters = [])
    {
        $this->faker = Faker::create();
    }


The Step

Here is one example but you could pass all your args through this

    /**
     * @Given /^I have the payload:$/
     */
    public function iHaveThePayload(PyStringNode $requestPayload)
    {
        $this->requestPayload = $this->checkForTokens($requestPayload);
    }

And The Scenario

  Scenario: Can Create a Person
    Given I have the payload:
    """
      { "data":
        {
           "email": "TOKEN_EMAIL",
           "roles": [
             { "id": "role-manager", "name": "Manager" }
           ]
         }
       }
    """

  Scenario: How do I get a token
    Given I have the payload:
    """
    {
      "password": "ADMIN_PASS",
      "grant_type": "password",
      "client_id": "CLIENT_ID",
      "client_secret": "CLIENT_SECRET",
      "username": "ADMIN_USERNAME"
    }
    """
    And I request "POST /oauth/access_token"
    Then I get a "200" response

I would like to also save the state of the token made so I can check that the update/post really worked etc. But for now this makes it super easy to not reseed with every step and not worry about duplicate ids.


Tags:

behat bdd