首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Rspec未初始化常量ActiveRecord(NameError)

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

Stack Overflow用户
提问于 2016-06-24 23:50:05
回答 3查看 2.3K关注 0票数 1

我学习了codeschool教程,但我遇到了一些麻烦。

这是zombie_spec.rb

代码语言:javascript
复制
#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

代码语言:javascript
复制
#spec/zombie.rb
class Zombie < ActiveRecord::Base 
    validates :name, presence: true
    ...
end

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

我已经把这个项目放到github上了

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-06-25 04:38:23

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

代码语言:javascript
复制
# 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
票数 1
EN

Stack Overflow用户

发布于 2016-06-25 00:16:04

Zombie正在扩展ActiveRecord::Base,但您的代码找不到ActiveRecord

要解决这个问题,您可以在zombie.rb中使用require 'activerecord'。根据是否已安装,您可能还需要从命令行执行gem install activerecord,或者将gem 'activerecord'添加到Gemfile并运行bundle install

票数 1
EN

Stack Overflow用户

发布于 2018-06-27 08:33:14

我找到了一个对我来说效果很好的例子:

代码语言:javascript
复制
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

我是ruby的新手,所以我不是百分之百确定它为什么需要这个":type“属性,但它解决了我的问题。

(Source)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38017379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档