Search code examples
phpcodeception

Use _beforeSuite() in Codeception


Good day! Please help me understand _beforeSuite($settings = array()) in Сodeception. I want to register the user before passing all the tests. I have a Tester class - MiddlewareTester, which describes the user registration method: Tests\Support\MiddlewareTester

<?php

namespace Tests\Support;

class MiddlewareTester extends Actor
{
    public function userRegister(UserDTO $user): void
        {
            $I = $this;

            $I->sendPostAsJson('/user/register', [
                'email' => $user->email,
            ]);
        }
    }

As I understand it, I need to create a Helper, and then write its name in the 'modules' block in codeception.yml:

Tests\Support\Helper\MiddlewareHelper

<?php

namespace Tests\Support\Helper;

class MiddlewareHelper extends \Codeception\Module
{
    public function _beforeSuite(array $settings = []) {
        $I = $this;

        $user = new User();

        $I->userRegister($user);
    }
}

codeception.yml

suites:
    middleware:
        actor: MiddlewareTester
        step_decorators:
          - \Codeception\Step\AsJson
        path: ./Middleware
        modules:
            enabled:
                - Tests\Support\Helper\MiddlewareHelper

Now I am getting errors:

  • Method 'userRegister' not found in MiddlewareHelper*

Please, tell me how to correctly pass tester methods to _beforeSuite? Thanks!

UPDATE

Gained access to the 'PhpBrowser' module from Helper

MiddlewareHelper

class MiddlewareHelper extends \Codeception\Module
{
    public function _beforeSuite(array $settings = []) {
        $I = $this;

        $user = new User();

        $I->getModule('PhpBrowser')->
        $response = json_decode($I->getModule('PhpBrowser')->_request('POST', '/user/register', ['email' => $user->email]));
}

But the problem is that the API endpoint accepts JSON. Earlier in MiddlewareTester POST requests were sent using the following method: $I->sendPostAsJson. Now, when using the '_request' method I get an error:

Unsupported Media Type

How to solve this problem?

UPDATE 2

Solved the problem by including the REST module and setting the headers

public function _beforeSuite(array $settings = []) {
        $I = $this;

        $user = new User();

        $moduleREST = $I->getModule('REST');

        $moduleREST->haveHttpHeader('Content-Type', 'application/json');

        $response = json_decode($moduleREST->sendPost('/user/register', ['email' => $user->email]))->data;

Solution

  • Move userRegister method to MiddlewareHelper. Modules can't access methods declared in Tester classes.

    Correct way to access methods of another module is by using getModule method, e.g. $db = $this->getModule('Db');. Helper is a module.

    See https://codeception.com/docs/ModulesAndHelpers#Accessing-Other-Modules