以下是我非常简单的能力课程:
class Ability
include CanCan::Ability
def initialize(user)
if user.has_role? :admin
can :manage, :control_panel
end
end
end我应该如何在控制器规范中模拟它?
这是我的控制面板控制器:
class Admin::ControlPanelController < ApplicationController
authorize_resource class: false
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, danger: "#{exception}"
end
def statistics
end
end这是我的control_panel控制器规范:
describe '#statistics:' do
let(:request){ get :statistics }
context 'When guest;' do
before do
# HOW SHOULD I MOCK HERE?
end
describe 'response' do
subject { response }
its(:status){ should eq 302 }
its(:content_type){ should eq 'text/html' }
it{ should redirect_to root_path }
end
describe 'flash' do
specify { expect( flash[:danger] ).to eq "You do not have sufficient priviledges to access the admin area. Try logging in with an account that has admin priviledges." }
end
end我该怎么嘲笑这个能力呢?以前,我做过这样的事情:
let(:user){ FactoryGirl.create :user }
expect(controller).to receive(:current_user).and_return user
expect(user).to receive(:has_role?).with(:admin).and_return false但那是在我使用cancan之前,手动检查用户是否有特定的角色。这种行为发生在应用程序控制器中,因此很容易模拟。我很难嘲笑这个能力班:
我想在不同的环境中嘲弄它。我觉得有点迷茫,因为即使我这样做:
expect(Ability).to receive(:asdasdadskjadawd?).at_least(:once)不会产生错误,但是如果我拼错了“异能”,就会产生一个错误,所以它在嘲弄这个班。
发布于 2014-09-06 19:32:08
我不认为您应该模拟Ability类,特别是在控制器测试中。Ability类更像配置而不是代码;在应用程序期间它不会改变。这也是控制器不应该关心的实现细节。
相反,您应该嘲笑您的Users。看起来您正在使用FactoryGirl;您可以使用工厂化女孩特质来模拟您拥有的各种用户:
FactoryGirl.define do
factory :user do
name 'Bob'
email 'bob@example.com
role 'user'
trait :admin do
role 'admin'
end
trait :guest do
role 'guest'
end
end
end然后,如果需要常规用户,可以使用FactoryGirl.create :user,如果测试需要管理员,则可以使用FactoryGirl.create :user, :admin。
https://stackoverflow.com/questions/25664018
复制相似问题