Search code examples
testinglaravelrelationshipscodeception

Codeception How to test if a User has a Role


I am trying to get into the habit of writing tests as I go. I am using Laravel 4.2 to build an application that registers Users and assigns different roles to different user types.

I want to write a test that will check to see if a User has a Role. I am using Entrust to manage my Roles/Permissions and Laracasts/TestDummy to generate dummy objects. The Roles are stored in a pivot table, so I am essentially testing for the existance of a many to many relationship The TestDummy documentation states that I need to define my objects and their relationships in a fixtures.yml file and gives an example

Post:
  title: Hello World $string
  body: $text
  published_at: $date
  author_id:
    type: Author

Author:
    name: John Doe $integer

The above layout defines a one to one relationship. A post has An Author. What I am trying to test for is A User has A Role, where many Users can have Many Roles

I want to know how to define this in my fixtures.yml file in my mind

If I wanted to test a Many to Many Relationship (Many Users have Many Roles) could I reference it like this?

Excel\Users\User:
  username: $string$integer
  email: $string$integer@example.com
  password: $string
  created_at: $date
  updated_at: $date

\Role:
  name: $string
  created_at: $date
  updated_at: $date

Assigned_Role:
  user_id:
    type: Excel\Users\User
  role_id:
    type: \Role

The problem as I see it is that Assigned_Role does not have a model as it is just a pivot table

How could I test if a User has a specific Role?


Solution

  • TestDummy only supports generating belongs to relations. You can try something like this, assuming you want to test a method on User like hasRole($role).

    $user = Factory::create('Excel\Users\User');
    $role = Factory::create('Role');
    
    $user->roles()->attach($role);
    $this->assertTrue($user->hasRole($role));
    
    $user->roles()->detach($role);
    $this->assertFalse($user->hasRole($role));