无法测试 belong_to,缺少 Rails 上的 ID 外键

Unable to test should belong_to, missing id foreign key on Rails

你好,我一直在寻找一种方法来测试模型关系并偶然发现 should gem

不幸的是,我试图用 rspec

来测试一个简单的例子
describe Region do
  it  "should have a city" do 
    should belong_to(:city)
  end
end

而且我总是收到

的消息
Region should have a city
     Failure/Error: should belong_to(:city)
       Expected Region to have a belongs_to association called city (Region does not have a city_id foreign key.)
     # ./spec/models/region_spec.rb:5:in `block (2 levels) in <top (required)>'

虽然我的人际关系出了点问题,但我已经测试成功地在 rails console 上创建了一个与城市相关联的区域。我一定是漏掉了什么!!

编辑模型和迁移

class Region < ActiveRecord::Base
    belongs_to :city
end


class City < ActiveRecord::Base
    validates :name, :presence => true
    has_many :regions
end

而且我在区域之后创建了城市,所以不得不稍微修改一下迁移文件:

class CreateCities < ActiveRecord::Migration
  def change
    create_table :cities do |t|
      t.string :name
      t.float :longitude
      t.float :latitude
      t.timestamps
    end

    add_reference :regions, :city, index: true, foreign_key: true

  end
end

schema.rb

  create_table "cities", force: true do |t|
    t.string   "name"
    t.float    "longitude"
    t.float    "latitude"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "regions", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "city_id"
  end

  add_index "regions", ["city_id"], name: "index_regions_on_city_id"
Region does not have a city_id foreign key.

你的错误信息很清楚的指出了问题所在。 因为,Region belongs_to a City,它期望 Region 模型中的 city_id foreign_key。

通过迁移在您的 Region 模型中添加一个 city_id 列,然后此测试将起作用! 我认为,shoulda gem 没有错。这只是您当前的模型设置。