October CMS resources and help articles

Simple and to the point. Optimized by the community.

Create new users in unit test

1
by cjk, last modified on April 12th, 2021

If you ever need to create a new user in your plugin unit tests, you first need to ensure early initialization of the Rainlab.User in your Plugin.php file, as below:

class Plugin extends PluginBase
{
    // make  sure the rainlab.user plugin is loaded already
    public $require = ['RainLab.User'];

    // ... continue with other initialization

Then, in your test class you can create new user:

        // create a user
        $this->user = User::create([
            'name' => 'Some User',
            'email' => 'test@test.com',
            'password' => 'changeme!!!',
            'password_confirmation' => 'changeme!!!'
        ]);

        // in order to log in as this user, we must be activated
        $this->user->is_activated = true;
        $this->user->activated_at = now();
        $this->user->save();

... and log-in as that user elsewhere in your unit tests:

        // register the auth facade
        $alias = AliasLoader::getInstance();
        $alias->alias('Auth', 'RainLab\User\Facades\Auth');

        App::singleton('user.auth', function() {
            return \RainLab\User\Classes\AuthManager::instance();
        });

        Auth::login($this->user);
        // we should now be authenticated
        $this->assertTrue(Auth::check());

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?