检验这一控制器的最佳方法是目前用户方法的 st。
For instance, we have the Product model and Products controller.
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