无法测试应该属于,在 Rails 上缺少 id 外键 [英] Unable to test should belong_to, missing id foreign key on Rails

查看:27
本文介绍了无法测试应该属于,在 Rails 上缺少 id 外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我一直在寻找一种方法来测试模型关系并偶然发现应该是宝石

Hello I have been looking for a way to test model relationship and stumble upon should gem

  • 应该 (3.5.0)
  • 应该-上下文 (1.2.1)
  • shouda-matchers (2.8.0)

不幸的是,我试图用 rspec 测试一个简单的例子

Unfortunatly I tried to test a simple example with 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 控制台 上创建了一个与城市相关联的区域.我一定是遗漏了什么!!

I though that there was something wrong with my relationships but I have test to create a Region with a city tied to it on rails console successfully. I must be missing something!!

编辑模型和迁移

class Region < ActiveRecord::Base
    belongs_to :city
end


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

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

And I created the city after the region so had to modify the migration file a bit:

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 是一个 City,它需要 Region 模型中的 city_id foreign_key.

Your error message clearly points out the problem. As, Region belongs_to a City, it's expecting a city_id foreign_key in Region Model.

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

Add a city_id column in your Region model by a migration and then this test will work! I think, nothing is wrong here with the shoulda gem. It's just your current model setup.

这篇关于无法测试应该属于,在 Rails 上缺少 id 外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆