2014-11-05 331 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 

,這就是它