0

我正在自学 RSpec (v3.1.7)。我已将 rspec 安装rails g rspec:install到现有的 Rails 应用程序中 - 新创建的。

我创建了一个模型:rails g rspec:model zombie. 运行迁移,一切顺利。

在:app/models/zombie.rb:

class Zombie < ActiveRecord::Base
   validates :name, presence: true
end  

在:app/spec/models/zombie_spec.rb:

require 'rails_helper'

RSpec.describe Zombie, :type => :model do
  it 'is invalid without a name' do
    zombie = Zombie.new
    zombie.should_not be_valid
  end  
end

当我运行时在终端(在应用程序目录中):rspec spec/models我得到:

F

Failures:

1) Zombie is invalid without a name
 Failure/Error: zombie.should_not be_valid
 NoMethodError:
   undefined method `name' for #<Zombie id: nil, created_at: nil, updated_at: nil>
 # ./spec/models/zombie_spec.rb:6:in `block (2 levels) in <top (required)>'

我按照视频教程进行操作,然后按照视频(使用 RSpec 进行测试)一直到后者。我喜欢在第2章减肥。我错过了什么吗?该视频是否使用旧版本的 rspec 作为视频教程?

在我的迁移文件中:

class CreateZombies < ActiveRecord::Migration
  def change
     create_table :zombies do |t|

      t.timestamps
     end
  end
end
4

2 回答 2

0

我认为您缺少 name 属性。以下迁移文件将为僵尸模型添加名称属性:

class AddNameToZombies < ActiveRecord::Migration
  def change
    add_column :zombies, :name, :string
  end
end

最后运行以下命令:

rake db:migrate

rake db:test:prepare

就是这样

于 2014-11-05T10:15:36.163 回答
0

您的模型不知道是什么name,因为您没有在迁移中定义属性:

class CreateZombies < ActiveRecord::Migration
  def change
     create_table :zombies do |t|
      t.string :name
      t.timestamps
     end
  end
end

然后运行:

rake db:migrate

那么这应该可以正常工作:

z = Zombie.new(name: 'foo')
z.name
 => 'foo'
于 2014-11-05T10:11:47.547 回答