'Testing associations with rspec: Category does not have a post_id foreign key

I'm trying to test some associations with RSpec but I get these failures:

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

Here's my model:

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

and my tests:

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

and my scheme

 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

Does anybody have any idea what's going on?



Solution 1:[1]

Without seeing your schema, it looks like your database tables are missing the foreign key columns. Creating a migration that adds the following should fix it:

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

Update

As I said in my comment below, also make sure you run rake db:test:prepare to ensure your test database has the most recent schema.

Solution 2:[2]

I had recently the same issue, but my schema was fine, the problem was that I were also specifying the inverse_of and it was wrongly spelled. It seems that in that case you also get this error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 eloyesp