2014-11-05 328 views
0

我自学RSpec(v3.1.7)。我已将rspec与rails g rspec:install安装到现有的Rails应用程序中 - 新创建。RSpec模型测试:失败

我创建了一个模型:rails g rspec:model zombie。冉移民,一切顺利。

在:应用/模型/ zombie.rb:

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

在:应用程序/规格/模型/ 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)>' 

Im和我跟着视频(测试使用RSpec)下降到LATT呃。我很喜欢第二章的减肥。我错过了什么吗?视频是否使用旧版rspec作为视频教程?

在我的移民文件:

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

     t.timestamps 
    end 
    end 
end 
+0

我已经创建了一个'attr_accessor:name'和它的工作原理是。但视频没有attr_accessor!我很失落! – Sylar 2014-11-05 09:33:02

+0

查看这两个链接:http://guides.rubyonrails.org/migrations.html#using-the-change-method adn http://guides.rubyonrails.org/migrations.html#running-migrations-in-different-环境 – jyrkim 2014-11-06 08:48:27

回答

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' 
+0

没有用。在提出问题之前,我曾尝试添加表名,但同样的事情。 – Sylar 2014-11-06 08:03:54

+0

好好努力,因为这是问题所在 – 2014-11-06 08:16:09

0

我认为你缺少名称属性。下面的迁移文件将名称属性添加到僵尸模式:

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

终于运行以下命令:

rake db:migrate 

rake db:test:prepare 

,这就是它