Ruby on Rails Friday, April 6, 2012

Colin Law wrote in post #1055228:
> On 6 April 2012 01:10, Fearless Fool <lists@ruby-forum.com> wrote:
>> - the first test fails with response.message = "Not Acceptable"
>> - the second test fails because count is not incremented.
>
> First look in test.log to see if there is any difference there, if
> still no joy then debug the create action to see what is going on.
> Look at the Rails Guide on Debugging if you don't know how to do this.
>
> Colin

Colin, thanks. To be clear, it appears that the #create method is
actually working. For the moment, I'm going to assume the first test is
okay and that the "Not Acceptable" response is an issue to chase down
later.

I see what's going on, but not how to fix the test: In the first test,
current_user.id = 1001. Ability#new gets called and sets up the
appropriate abilities. On the second test, current_user.id = 1002, but
Ability#new doesn't get called. (Is it cached?) When it tries to
create a premise object, CanCan's load_and_authorize_resource method
creates a Premise with user_id = 1001, which subsequently fails because
current_user's id = 1002.

So the short question: Why isn't Ability#new getting called in every
test? Or what must I do to set up the abilities?

You can stop reading here if you understand the question. :) Gory
details follow:

My Abilities class has (effectively):

# file: app/models/ability.rb
class Ability
def initialize(user)
can :manage, Premise, :user_id => user.id
end
end

meaning that access to a Premise is limited to its owner. My
PremisesController has:

# file: app/controllers/premises_controller.rb
class PremisesController < ApplicationController
load_and_authorize_resource
respond_to :json

def create
@premise.save!
respond_with @premise
end
end

In the first test:

current_user.id = 1001
Ability#new gets called with current_user
arguments to Premise#initialize = {:user_id => 1001, ...}

In the second test:

current_user.id = 1002
Ability#new does NOT get called
arguments to Premise#initialize = {:user_id => 1001, ...}

... which leads to a CanCan::AccessDenied error, since premise.user_id
!= current_user.id

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment