2012-11-18 70 views
2

我想要測試一些協會與RSpec的,但我得到這些故障:測試協會使用RSpec:類別沒有POST_ID外鍵

Category 
    Failure/Error: it {should belong_to :post} 
    Expected Category to have a belongs_to association called post (Category does not have a post_id foreign key.) 
# ./spec/models/category_spec.rb:7:in `block (2 levels) in <top (required)>' 

Post 
Failure/Error: it {should have_one (:category)} 
    Expected Post to have a has_one association called category (Category does not have a post_id foreign key.) 
# ./spec/models/post_spec.rb:8:in `block (2 levels) in <top (required)>' 

這裏是我的模型:

class Post < ActiveRecord::Base 
    has_one :category 
    validates_presence_of :author, :category, :post 
end 

class Category < ActiveRecord::Base 
    belongs_to :post 
    validates_presence_of :name 
end 

和我的測試:

require 'spec_helper' 

describe Post do 
    it {should validate_presence_of(:author)} 
    it {should validate_presence_of(:post)} 
    it {should validate_presence_of(:cathegory)} 
    it {should have_one (:category)} 
end 

describe Category do 
    it {should validate_presence_of :name} 
    it {should belong_to :post} 
end 

和我的方案

ActiveRecord::Schema.define(:version => 20121118131441) do 

    create_table "categories", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.integer "post_id" 
    end 

    create_table "posts", :force => true do |t| 
    t.string "author" 
    t.string "cathegory" 
    t.text  "post" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.integer "category_id" 
    end 

end 

有沒有人知道發生了什麼事?

+3

你可以發佈你的模式嗎? –

+0

對於has_one/belongs_to,您不需要雙方的按鍵我會說它應該發佈belongs_to類別(並有一個category_id列),而類別has_many帖子。 –

回答

5

沒有看到您的模式,它看起來像您的數據庫表缺少外鍵列。創建遷移,增加了以下內容應該修復它:

add_column :categories, :post_id 
add_column :posts, :category_id 

更新

正如我在我下面的評論說,還要確保你運行rake db:test:prepare以確保您的測試數據庫具有最新的架構。

+0

它看起來像你有類別的外鍵,但不是後外鍵,所以你仍然需要'add_column:posts,:category_id'。我本來會期望其中一個測試通過,測試數據庫是否與您的模式過時了?你可以嘗試運行'rake db:test:prepare' –

+0

嗯,我做了你要求做的事,但沒有奏效。我把我的模式放在我的帖子上。 –

+0

我第一次看到它時沒有看到category_id,但模式看起來正確。 –