Quick way to mock data for Behat in Laravel

Posted: 2015-03-30 00:05:20

Below allows me to use this type of step in my tests

Scenario: Given I update a Domain get 200        
    Given I mock "App\Sites\Domain" with properties:                                          
      """
      id: "mock-update-1"
      site_id: "mock-site-1"
      domain: "foo2.com
      """
    Given I have the payload:                                                                                 
      """
        {
          "data":
          {
            "id":      "mock-update-1",
            "site_id": "mock-site-1",
            "domain":   "foo2.com"
          }
        }
      """
    Then I request "PUT /api/v1/sites/mock-site-1/domains/mock-update-1"
    Then I get a "200" response                                                                 

Here is the code in my FeatureContext.php

    /**
     * @Given I mock :arg1 with properties:
     */
    public function iMockWithProperties($model, PyStringNode $properties)
    {
        try
        {
            $this->setModel($model);
            $this->makeFields($properties);
            $this->removeMockIfExists();


            $this->checkModelForTimeStamps();

            $this->createMock();
        }
        catch(\Exception $e)
        {
            $this->printDebug(sprintf("Error making mock", $e->getMessage()));
        }
    } 

    private function checkModelForTimeStamps()
    {
        if($this->getModel()->timestamps)
        {
            $dateTime = new DateTime('-3 day');
            $created_at = $dateTime->format('Y-m-d H:i:s');
            $this->fields['created_at'] = $created_at;
            $this->fields['updated_at'] = $created_at;
        }
    }

    protected function removeMockIfExists()
    {
        if(isset($this->fields['id']) && $results = $this->getModel()->find($this->fields['id']))
            $results->delete();
    }

    protected function makeFields($properties)
    {
        foreach($properties->getStrings() as $value)
        {
            $field = explode(":", $value);
            $this->fields[trim($field[0])] = str_replace('"', '', trim($field[1]));
        }    
    }

    public function createMock()
    {
        $this->getModel()->create($this->fields);
    }

    /**
     * @return mixed
     */
    public function getFields()
    {
        return $this->fields;
    }

    /**
     * @param mixed $fields
     */
    public function setFields($fields)
    {
        $this->fields = $fields;
    }

    /**
     * @return mixed
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * @param mixed $model
     */
    public function setModel($model)
    {
        $this->model = new $model;
    }

Tags:

laravel php behat