我学习了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上了
发布于 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
。
# 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
发布于 2016-06-25 00:16:04
Zombie
正在扩展ActiveRecord::Base
,但您的代码找不到ActiveRecord
。
要解决这个问题,您可以在zombie.rb
中使用require 'activerecord'
。根据是否已安装,您可能还需要从命令行执行gem install activerecord
,或者将gem 'activerecord'
添加到Gemfile
并运行bundle install
发布于 2018-06-27 08:33:14
我找到了一个对我来说效果很好的例子:
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)
https://stackoverflow.com/questions/38017379
复制相似问题