Rspec未初始化的常量ActiveRecord(NameError)

时间:2016-06-24 15:50:05

标签: ruby-on-rails ruby activerecord rspec

我遵循了codeschool教程,但我遇到了一些麻烦。

这是 zombie_spec.rb

#spec/model/zombie_spec.rb
require 'spec_helper'
require 'zombie'


describe Zombie do
it 'is invalid without a name' do
    zombie = Zombie.new 
    zombie.should_not be_valid
    end     
end

zombie.rb

#spec/zombie.rb
class Zombie < ActiveRecord::Base 
    validates :name, presence: true
    ...
end

输入rspec spec/models/zombie_spec.rb后,它会抛出uninitialized constant ActiveRecord (NameError)

我已将此项目放在github

3 个答案:

答案 0 :(得分:1)

Zombie正在延长ActiveRecord::Base,但您的代码无法找到ActiveRecord

要修复require 'activerecord' zombie.rb内的gem install activerecord。根据是否已安装,您可能还需要从命令行gem 'activerecord',或者将Gemfile添加到bundle install并运行import android.test.InstrumentationTestCase; public class exampleTest extends InstrumentationTestCase { String ob1, ob2; public void setUp() throws Exception { super.setUp(); ob1 = "hi"; ob2 = "bye"; } public void testEx()throws Exception{ assertEquals("Error", ob1, ob2); } }

答案 1 :(得分:0)

我认为本教程可能试图从在普通Ruby对象上使用RSpec过渡到在ActiveRecord对象上使用rspec-rails gem。对于使用rspec-rails的示例,您应该在文件app/models/zombie.rb中有一个模型。这就是spec/models/zombie_spec.rb中的规范所要求的内容。此外,您的规范需要rails_helper而不是spec_helper

# app/models/zombie.rb
class Zombie < ActiveRecord::Base

  validates :name, presence: true

  def hungry?
    true
  end
end

# spec/models/zombie_spec.rb
require 'rails_helper'

describe Zombie do
  it 'is invalid without a name' do
    zombie = Zombie.new
    zombie.should_not be_valid
  end
end

答案 2 :(得分:0)

我找到了一个对我有用的例子:

require 'rails_helper'

RSpec.describe Auction, :type => :model do
  it "is valid with valid attributes"
  it "is not valid without a title"
  it "is not valid without a description"
  it "is not valid without a start_date"
  it "is not valid without a end_date"
end

我是红宝石的新手,所以我不确定100%为什么它需要此“:type”属性,但是它解决了我的问题。

Source