2
votes

I try to testing 'cancan' gem.But when I running rspec, shell show me an error

uninitialized constant Ability (NameError)

this is my spec_ability.rb

require 'spec_helper'
require "cancan/matchers"

describe Ability do
  it "user has ability" do
    user = FactoryGirl.create(:user)
    ability = Ability.new(user)
    expect(ability).to be_able_to(:destroy, Project.new(:user => user))
  end
end

and this is model ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end

full trace

/home/weare138/timonin/spec/models/ability_spec.rb:4:in `<top (required)>': uninitialized constant Ability (NameError)
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `load'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `block in load_spec_files'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `each'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `load_spec_files'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:96:in `setup'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:84:in `run'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:69:in `run'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:37:in `invoke'
    from /home/weare138/.rvm/gems/ruby-2.1.5/gems/rspec-core-3.1.7/exe/rspec:4:in `<top (required)>'
    from /home/weare138/.rvm/gems/ruby-2.1.5/bin/rspec:23:in `load'
    from /home/weare138/.rvm/gems/ruby-2.1.5/bin/rspec:23:in `<main>'
    from /home/weare138/.rvm/gems/ruby-2.1.5/bin/ruby_executable_hooks:15:in `eval'
    from /home/weare138/.rvm/gems/ruby-2.1.5/bin/ruby_executable_hooks:15:in `<main>'

users was generated factory 'users.rb'

how fix?

sorry for my bad English

1
In which folder did you place the ability.rb?fivedigit
what RSpec version do you use? if '3.x' then try to change require 'spec_helper' to require 'rails_helper'gotva
2fiveigit in models folder, 2gotva 3.1.0.vveare138

1 Answers

2
votes

The easiest fix for this would indeed be to require 'rails_helper' instead of require 'spec_helper'.

This will load the Rails stuff, and will add the Ability class to the load path. Then it can be auto loaded when used in the spec.

Alternatively, you could load the ability class manually in your spec:

require_relative '../../app/models/ability'