mercredi 28 novembre 2018

Rspec Test CanCan AbilityClass not building rules in Rails3.2

In my Test environment Cancan does not build its rules.

ability.rb

class Ability
 include CanCan::Ability

  def initialize(user)
    user ||= User.new 

    if user.is_admin?
      can :manage, :all
    end
    ....
  end
 end

When i start the development console and i do the following

 u = User.where(role: "admin").first
 u.ability.can?(:read, Order)        #true
 a = Ability.new(u)
 a.instance_values["rules"]          #gives [0] #<CanCan::Rule:0x000055f2637ece48 @match_all=false, @base_behavior=true, @actions=[:read], @subjects=[Order(id: integer, ....

shows that everything works fine. The rules are set. Doing the same in rails c test the a.instance_values["rules"] is empty

 u = User.where(role: "admin").first
 u.ability.can?(:read, Order)        #false
 a = Ability.new(u)
 a.instance_values["rules"]          #gives [] 

As a result the test

RSpec.describe Ability do
  describe 'User' do
    describe "abilities" do
      context "when is an  Admin" do
       subject(:admin){ AdminAbility.new(create(:admin_user)) }
         it do  
           puts admin.can? :read, Order #false
           puts admin.ability.can? :read, Order #false
           expect(admin).to be_able_to(:read, Order)
         end 
         it {expect(admin).to be_able_to(:read, User) }
        end 
       end 
      end 
    end

fails not suprisingly with

** Failure/Error: it {expect(admim).to be_able_to(:read, Order)}
   expected to be able to :read Order(...)**

CanCan build the rules correctly for the development environment (I tested the FactorySetup for the roles and the Adminuser, this is not the problem)

Setup: Rails: 3.2.22.2 Rspec: 3.8 CanCan: 1.6.10

Aucun commentaire:

Enregistrer un commentaire