[英]Rails 3: How to create rspec controller specs when using cancan's automatic resource loading?
I'm missing something here.... 我在这里错过了一些东西。
Cancan has a neat feature to automatically load your resources: Cancan具有一项巧妙的功能,可以自动加载您的资源:
(taken from https://github.com/ryanb/cancan/wiki/Authorizing-Controller-Actions ) (摘自https://github.com/ryanb/cancan/wiki/Authorizing-Controller-Actions )
def index
# @products automatically set to Product.accessible_by(current_ability)
end
Except I can't figure out how to get this to work in my rspec controller specs... 除非我无法弄清楚如何使其在我的rspec控制器规格中起作用...
It's probably very simple and I'm just brain-frazzled at the moment. 这可能很简单,此刻我只是脑子发呆。 : P Anyway, it comes from cancan's load_and_authorize_resource
function. :P无论如何,它来自cancan的load_and_authorize_resource
函数。
Ideas? 想法? Thanks! 谢谢!
The best way to test this controller is a stub the current_user method. 测试此控制器的最佳方法是对current_user方法进行存根。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.