I am trying to create rspec test for ability class. I successfully wrote the ability for the admin and testing this, but I don't know how write the test for the login user(login user can only update and destroy its own comments).
This is ability.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
and this is ability_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
Add this code in your spec_helper RSpec.configure.
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
...
end
This is to use devise helper in your specs. like sign_in(user). So, for testing logged in user you can first sign the user like this
it "user admin" do
user = FactoryGirl.create(:user, role: 'admin')
sign_in(user)
# your code to test update and destroy ability
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.