Search code examples
phpsymfonybehat

Behat: How to clean up database records created in the scenario


I have the following scenario:

    @mink:selenium2
  Scenario: Login
    Given there are the following users:
      | username | password | email               |
      | admin    | 1234     | admin@socialcar.com |
    When I am on "/login"
    And I fill in "username" with "admin"
    And I fill in "password" with "1234"
    And I press "Login"
    Then I should be on "/admin"

So I'd like to have a cleanupUsers as a @AfterScenario where I can clean whatever was inserted in the scenario. So how can I access the TableNode of users?


Solution

  • You can save your users in a private property so that you could access them later in a hook:

    private $users;
    
    /**
     * @Given there are the following users:
     */
    public function thereAreFollowingUsers(TableNode $table)
    {
        $this->users = $table;
    
        // ...
    }
    
    /**
     * @AfterScenario
     */
    public function cleanupUsers(AfterScenarioScope $scope)
    {
        if (null !== $this->users) {
            // do the cleanups
            // ...
    
            // reset the property
            $this->users = null;
        }
    }