作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试测试一些与 RSpec 的关联,但我遇到了这些失败:
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
有人知道发生了什么事吗?
最佳答案
没有看到您的架构,看起来您的数据库表缺少外键列。创建一个添加以下内容的迁移应该可以修复它:
add_column :categories, :post_id
add_column :posts, :category_id
更新
正如我在下面的评论中所说,还要确保您运行 rake db:test:prepare
以确保您的测试数据库具有最新的架构。
关于ruby-on-rails - 测试与 rspec : Category does not have a post_id foreign key 的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13440122/
我是一名优秀的程序员,十分优秀!