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
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'
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.