无法测试 should follow_to,Rails 上缺少 id 外键

2023-12-21

你好,我一直在寻找一种测试模型关系的方法并偶然发现应该宝石 https://github.com/thoughtbot/shoulda

  • 应该 (3.5.0)
  • 应该上下文 (1.2.1)
  • 应该匹配器 (2.8.0)

不幸的是我试图用 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

模式.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 属于 a City,它期待一个city_id外键输入Region Model.

Add a city_id列在你的Region通过迁移建立模型,然后这个测试就会起作用! 我认为,这里没有什么问题shoulda宝石。这只是您当前的模型设置。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法测试 should follow_to,Rails 上缺少 id 外键 的相关文章

随机推荐