2012-11-18 5 views
2

내가 RSpec에 일부 연결을 테스트하기 위해 노력하고있어하지만 난이 오류를 얻을 :시험 협회 : 카테고리가없는 post_id를 외래 키

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 

:

여기
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)>' 

내 모델의 내 테스트 :

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에 대해서는 양쪽에 키가 필요하지 않습니다. 범주는 has_many posts 인 반면, 게시물은 belongs_to category (category_id 열을가집니다)라고해야합니다. –

답변

5

스키마가 표시되지 않으면 데이터베이스 테이블에 외래 키 열이 누락 된 것처럼 보입니다. 다음 사항을 추가하는 마이그레이션을 만들기를 해결해야합니다

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

업데이트

내가 아래에있는 내 의견에 말했듯이, 또한 당신의 테스트 데이터베이스는 가장 최근의 스키마를 가지고 있도록 rake db:test:prepare를 실행해야합니다.

+0

카테고리 외래 키를 가지고 있지만 외래 키를 포스팅 한 것이 아닌 것처럼 보입니다. 그래야 여전히'add_column : posts, : category_id'가 필요합니다. 테스트 중 하나가 통과 할 것으로 예상 했었습니까? 테스트 DB가 스키마와 함께 구식입니까? 'rake db : test : prepare'를 실행 해 볼 수 있습니다. –

+0

글쎄, 내가 한 일은 당신이 한 일 이었지만 작동하지 않았습니다. 내 스키마에 내 글을 올렸습니다. –

+0

내가 처음 보았을 때 category_id가 보이지 않았지만 스키마가 올바르게 보입니다. –