1
votes

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)
1
you might want to try out CanCanCan for Rails 4. It is the continued version of CanCan since it is out of date.nayiaw
I would have but I am currently on a project running for many years so I am not allowed to upgrade to CanCanCan.illusionist

1 Answers

1
votes

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