intosite's avatar

How do i test Login Flow?

Trying to test my Login flow. Currently i have 3 types of roles for users, "super-admin", "site-admin", "regular-user" and guest

I tried this, but am uncertain how to inject the "super-admin" roles into the hasRole function.

$user = m::mock(User::class, [
                'hasRole' => true ] );
 $this->actingAs($user)
             ->visit('/')
             ->see('Content');
0 likes
5 replies
ifpingram's avatar

What's your code for the role part of the User model please?

intosite's avatar

My User model,

class User extends Model implements AuthenticatableContract,  AuthorizableContract,    CanResetPasswordContract
{
        use Authenticatable, Authorizable, CanResetPassword, RolesTrait;
    ...
}

My RolesTrait contains the hasRole () function

trait RolesTrait {
    public function hasRole($role) {
        if (is_string($role)) {
            return $this->roles->contains('name', $role);
        }

        return !! $role->intersect($this->roles)->count(); 
    }
...
intosite's avatar

I just updated my routes and I get 58lines of error on the test. New Route - (is there a better way to do this?)

Route::get('/', function () {
    if (Auth::check()) {
        $user = Auth::user();
        if ($user->hasRole(  "super-admin") || $user->hasRole(  "gym-admin") ) {
            return redirect('/home');
        }
    }
   return redirect('/routes');
});
ifpingram's avatar

Are you looking to TDD (test first to drive out your design), or to test after (to validate 'state' and that your code does what you expect)? Your first post implied the former, but you last one the latter. I'm a little confused. Whichever approach you use, it is best to stick with it, or you will not get into a good flow and end up confusing yourself. It now seems you have 2 distinct questions. :) Do you still want me to try to answer the first one?

FWIW I would take the TDD approach - it will drive out the good design.

intosite's avatar

Erm, sorry I don't really understand your question. I'm not a programmer by training, and have very little idea on design concepts. I'm currently learning by looking at tutorials & code samples while trying to fiddle them into what I'm planning to do. So i guess what I'm doing will be probably be a mash up of whoever's design pattern I'm currently following.

I would like to think that if possible to learn the best practises so to get a good foundation.

Currently I manage to get my checks to validate my state. I did it by changing my test function to,

$user = new User(array('name' => 'John'));
        $mockUser = m::mock($user);
        $mockUser->shouldReceive('hasRole')
          ->andReturn(true);

        $this->actingAs($mockUser)
             ->withSession(['foo' => 'bar'])
             ->visit('/')
             ->see('<b>Tracker</b> Profile');

I don't understand why would that work instead of the bottom?

$mockUser = m::mock(User::class);

Please or to participate in this conversation.