Rails 3:如何在使用cancan的自动资源加载时创建rspec控制器规范?

时间:2011-11-08 22:52:55

标签: ruby-on-rails rspec cancan

我在这里错过了什么....

Cancan具有自动加载资源的简洁功能:

(摘自https://github.com/ryanb/cancan/wiki/Authorizing-Controller-Actions

def index
  # @products automatically set to Product.accessible_by(current_ability)
end

除了我无法弄清楚如何在我的rspec控制器规范中使用它...

这可能非常简单,我现在只是脑筋疲惫。 :P无论如何,它来自cancan的load_and_authorize_resource函数。

想法?谢谢!

1 个答案:

答案 0 :(得分:1)

测试此控制器的最佳方法是使用current_user方法存根。

例如,我们有产品型号和产品控制器。

class Product < ActiveRecord::Base 
end

class ProductsContoller < ApplicationController
  load_and_authorize_resource

  def index
  end

end

# allow access to Product only for admin user
class Ability
  include CanCan::Ability

  def initialize(user)

    user ||= User.new

    if user.admin?
      can :manage, Product
    end  

  end
end


# stubbing current_user method
module ControllersHelper
  def current_user!(user)
    raise "argument not valid" unless user.is_a?(User)
    controller.stub!(:current_user).and_return(user)
  end
end

# and include this method to rspec config
Spec::Runner.configure do |config|
  config.include ControllersHelper, :type => :controller
end


describe ProductsContoller do
  before do
    current_user!(user)
  end
  let(:user) { Factory(:user) }

  describe "GET index" do

    describe "for admin users" do
      before do
        user.update_attribute(:admin, true)
      end  

      it "should find .products tag" do
        get products_path
        response.should have_tag ".products"
      end  
    end  

    describe "for guest users" do
      it "should find .products tag" do
        get products_path
        response.should_not be_success
      end  
    end
  end
end