【问题标题】:Unable to test should belong_to, missing id foreign key on Rails无法测试应该属于_to,Rails 上缺少 id 外键
【发布时间】:2015-11-12 03:47:35
【问题描述】:

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

  • 应该 (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

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"

【问题讨论】:

  • 您需要发布您的RegionCity 模型以及schema.rb 的相关部分,以便我们评估您的数据设置是否正确。
  • 再次请发布您的地区和城市的 schema.rb,而不是您的城市迁移。最后请提供您使用的 Rails 和 Shoulda 版本。

标签: ruby-on-rails ruby rspec shoulda


【解决方案1】:
Region does not have a city_id foreign key.

您的错误消息清楚地指出了问题所在。 正如Region belongs_toCity,它在Region 模型中期待city_idforeign_key。

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

【讨论】:

  • 是的,它看起来确实很清楚,但我仍然需要弄清楚原因,因为我能够将区域链接到城市,检查 schema.rb 和数据库,我可以看到 city_id integer 字段,
  • 你真的需要add_reference :regions, :city, index: true, foreign_key: true 来添加你的外键吗?这可能是一个问题。可能存在 gem 版本兼容性问题。我找不到任何东西。仍然在尝试。同时,尝试删除该行,只保留regions 表中的city_id 列和您已经拥有的正确关联。然后尝试。告诉我!
  • 我刚想到一件事。你跑了吗:RAILS_ENV=test rake db:migrate?可能是您的测试数据库在regions 表中没有city_id。请对此进行测试并告诉我!尝试:RAILS_ENV=test bundle exec rails c 然后尝试创建一个Region,并在rails 控制台上绑定一个city(指向测试数据库)。让我知道。
猜你喜欢
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多