简体   繁体   中英

I was trying write permissions specs for CanCan by RyanBates but got error “uninitialized constant Ability::CanCan”

I dont think this issue CanCan uninitialized constant Ability::CanCan addresses my problem.

According to CanCan Its not hard to test the Abilities . I followed https://github.com/ryanb/cancan/wiki/Testing-Abilities to write specs:

When I try the following command

bundle exec rspec spec/cancan/ability.rb 

I get the following error

/projects/ATS/app/models/ability.rb:2:in `<class:Ability>': uninitialized constant Ability::CanCan (NameError)
        from /home/shiva/projects/ATS/app/models/ability.rb:1:in `<top (required)>'
        from /home/shiva/projects/ATS/spec/cancan/ability.rb:3:in `<top (required)>'
from /home/shiva/.rvm/gems/ruby-2.1.1/gems/cancan-1.6.10/lib/cancan.rb:1:in `<top (required)>'
        from /home/shiva/projects/ATS/spec/rails_helper.rb:14:in `<top (required)>'
        from /home/shiva/projects/ATS/spec/cancan/ability.rb:1:in `<top (required)>'

My code in spec/cancan/ability.rb

require 'rails_helper'

RSpec.describe Ability, type: :model do
  subject(:ability) {Ability.new(user)}
  let(:user) {nil}
  context 'Logged in as CSA' do
    let(:org) {create(:organization)}
    let(:user) {create(:user, organization: org, role_ids: [Role::ROLE_CSA])}
    describe 'Not Permitted' do
      it 'to visit /admins' do
          it {is_expected.to be_able_to(:manage, Workflow.new)}
      end

    end
  end
end

and code in snippet in models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user, url, admin_session_id, my_applicant_id)
    if user.present?
      user.roles[0].permissions_by_organization(user).each do |permission|
        case permission.subject_class

Version Details of components

  • Rails 4.0.4
  • rspec-core (3.1.7)
  • rspec-expectations (3.1.2)
  • rspec-mocks (3.1.3)
  • rspec-rails (3.1.0)
  • rspec-support (3.1.2)
  • cancan (1.6.10)

I got the answer for my question.

The issue was the filename of the spec file It should have been
spec/cancan/ability_spec.rb but it was
spec/cancan/ability.rb

and I should have invoked
bundle exec rspec spec/cancan/ability_spec.rb

For more details please visit this link RSpec naming conventions for files and directory structure

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM