Ruby on rails 登录用户的Rspec测试.CanCan
我正在尝试为能力类创建rspec测试。我成功地为管理员编写了这个功能并进行了测试,但我不知道如何为登录用户编写测试(登录用户只能更新和销毁自己的注释) 这是ability.rb:Ruby on rails 登录用户的Rspec测试.CanCan,ruby-on-rails,rspec,cancan,Ruby On Rails,Rspec,Cancan,我正在尝试为能力类创建rspec测试。我成功地为管理员编写了这个功能并进行了测试,但我不知道如何为登录用户编写测试(登录用户只能更新和销毁自己的注释) 这是ability.rb: class Ability include CanCan::Ability def initialize(user) user ||= User.new if user.admin? can :manage, :all
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
这是能力规格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\u helper RSpec.configure中添加此代码
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
...
end
这是在您的规格中使用Desive helper。如登录(用户)。
因此,对于测试登录用户,您可以首先对用户进行签名
像这样
it "user admin" do
user = FactoryGirl.create(:user, role: 'admin')
sign_in(user)
# your code to test update and destroy ability
end
我知道这确实回答了你的问题,但我认为适当的PSA是合适的。避免使用Cancan,因为gem不再被积极维护。它已经一年多没有更新了,也没有针对Rails 4+进行全面测试。我建议使用CanCanCan(原始项目的一个分支)或Pundit。谢谢你,伙计,但我只需要CanCan