我尝试测试cancan' gem.But当我运行rspec时,shell显示错误
uninitialized constant Ability (NameError)
这是我的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
这是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
完整追踪
/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>'
用户已生成工厂&#39; users.rb&#39;
如何解决?
抱歉我的英文不好
答案 0 :(得分:2)
对此最简单的解决方法确实是require 'rails_helper'
而不是require 'spec_helper'
。
这将加载Rails的东西,并将Ability
类添加到加载路径。然后在规范中使用时可以自动加载。
或者,您可以在规范中手动加载能力类:
require_relative '../../app/models/ability'