Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Testing a user can only list the users of her group #549

Closed
afriqs opened this Issue · 3 comments

2 participants

@afriqs

Hi,

Well, I managed I think to implement such behavior (I tested the app) but unfortunately I did not manage to test it using RSpec :(

Imagine a User belongs to one Group and that the Group has many Users.

My UserController

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
  end
end

My UserAbility

class UserAbility
  include CanCan::Ability

  def initialize(user)
    if user
      can :index, User, :group_id => user.group.id
    end
  end
end

And finally the tests which fail

it "should be able to list all the users of her group" do
  @group = Fabricate(:group)
  @user = Fabricate(:user, :group => @group)
  @ability = UserAbility.new(@user)
  # Following does not work :(
  @ability.should be_able_to(:index, @group.users)
  @ability.should be_able_to(:index, User.where(:group_id => @group.id))
end

If any of you has an any how to accurately test such a behavior ;-))

Note : Rails 3.1.3, Cancan 1.6.7, RSpec 2.8.0

Cheers

@brutuscat

I'm having the exact same issue using RoR 3.1.2

the #can? method does not work as expected against an ActiveRecord Relation. However if you do:

@ability.should be_able_to(:index, @group.users.first)

Does work.

@afriqs

Thanks a lot @brutuscat , I confirm it works like this, also with Rails 3.2.0 ;-)

Regards.

@afriqs afriqs closed this
@brutuscat

There is an important issue I think: If the group does not have any user it will always return false

So I think you should do something like this:

can :index_user, Group, :id => user.group.id

And then

@ability = Ability.new(@user.group)
....
@ability.should be_able_to(:index_user, @group)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.