[rspec-users] how to mock/stub restful_authenticated and acl2-ized actions

Chris Flipse cflipse at gmail.com
Tue Apr 8 22:03:00 EDT 2008


On Tue, Apr 8, 2008 at 10:03 AM, Giuseppe Bertini <lists at ruby-forum.com>
wrote:

> Dear all,
>
> I am wondering how to properly mock/stub out the preliminary steps to
> actions protected by restful_authentication and acl_system2 (role-based
> authorization to execute actions). Here's my setup:
>

I use a different authorization plugin, so you might have to adapt, but I've
got the following in my spec_helper:

def as_role(roles = [])
  returning User.new do |user|
    # This will become stub_model whenever 1.1.4 comes out ...
    user.id = 2000
    user.stub!(:new_record?).and_return false
    user.stub!(:valid?).and_return true

    if @controller
      @controller.stub!(:login_required).and_return true
      @controller.stub!(:current_user).and_return true
      @controller.stub!(:logged_in?).and_return true
    end

    user.stub!(:has_role?).and_return false  # because has_role? hits the DB
    [*roles].map(&:to_s).each do |role|
      user.stub!("is_#{role}?").and_return true
      user.stub!(:has_role?).with(role).and_return true
    end
  end
end
alias :logged_in :as_role


This returns a User, and can be used in either the controller or in model
specs, to deal with various aspects of a roled user.  You can call it with
an array of roles, or a single role; it deals with it either way.  The last
alias is because logged_in looks better than as_role without any arguments.


-- 
// anything worth taking seriously is worth making fun of
// http://blog.devcaffeine.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://rubyforge.org/pipermail/rspec-users/attachments/20080408/386d7bbd/attachment-0001.html 


More information about the rspec-users mailing list