简体   繁体   English

Rspec测试“ cancan”。 未初始化的常数Ability(NameError)

[英]Rspec test 'cancan'. Uninitialized constant Ability (NameError)

I try to testing 'cancan' gem.But when I running rspec, shell show me an error 我尝试测试'cancan'gem。但是当我运行rspec时,shell向我显示错误

uninitialized constant Ability (NameError)

this is my spec_ability.rb 这是我的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 这是模型capability.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' 用户生成工厂'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' . 最简单的解决方法确实是require 'rails_helper'而不是require 'spec_helper'

This will load the Rails stuff, and will add the Ability class to the load path. 这将加载Rails内容,并将Ability类添加到加载路径。 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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