[英]Rspec test for login user.CanCan
我正在尝试为能力课程创建rspec测试。 我已经成功地为管理员编写了该功能并对其进行了测试,但是我不知道如何为登录用户编写测试(登录用户只能更新和销毁其自己的注释)。
这是capability.rb:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :all
else
can :read, :all
can :create, :update, :destroy, Comment, user_id: user.id
end
end
end
这是capability_spec.rb:
require 'rails_helper'
require "cancan/matchers"
describe Ability do
it "user guest" do
user = FactoryGirl.create(:user)
ability = Ability.new(user)
comment = Comment.new(user: user)
expect(ability).to be_able_to(:read, comment)
end
it "user admin" do
user = FactoryGirl.create(:user, role: 'admin')
ability = Ability.new(user)
comment = Comment.new(user: user)
expect(ability).to be_able_to(:destroy, comment)
end
将此代码添加到您的spec_helper RSpec.configure中。
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
...
end
这是在您的规格中使用devise助手。 像sign_in(user)。 因此,对于测试登录用户,您可以先像这样对用户进行签名
it "user admin" do
user = FactoryGirl.create(:user, role: 'admin')
sign_in(user)
# your code to test update and destroy ability
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.