Ruby on rails 无法测试应属于\u,Rails上缺少id外键
您好,我一直在寻找一种方法来测试模型关系,并偶然发现Ruby on rails 无法测试应属于\u,Rails上缺少id外键,ruby-on-rails,ruby,rspec,shoulda,Ruby On Rails,Ruby,Rspec,Shoulda,您好,我一直在寻找一种方法来测试模型关系,并偶然发现 shoulda(3.5.0) shoulda上下文(1.2.1) shoulda matchers(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/E
- shoulda(3.5.0)
- shoulda上下文(1.2.1)
- shoulda matchers(2.8.0)
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)>'
我在区域之后创建了城市,因此不得不稍微修改迁移文件:
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
您的错误消息清楚地指出了问题所在。
由于,Region
属于一个City
,因此在Region
模型中需要一个城市id
外键
通过迁移在您的区域
模型中添加一个city\u id
列,然后该测试就可以工作了!
我认为,
shoulda
gem在这里没有什么问题。这只是您当前的模型设置。您需要发布您的地区
和城市
模型以及模式的相关部分。rb
以便我们评估您的数据是否正确设置。再次,请发布您的schema.rb区域和城市,而不是城市迁移。最后,请提供您使用的Rails和Shoulda的版本。是的,这看起来很清楚,但我仍然需要找出原因,因为我能够将一个区域链接到一个城市,检查schema.rb和数据库,我可以看到一个city\u id integer
字段,您真的需要add\u参考:regions,:city,index:true,外键:true
添加外键?这可能是个问题。可能存在gem版本兼容性问题。但是我在上面找不到任何东西。还在努力。同时,尝试删除该行,只需在regions
表中保留city\u id
列以及您已经拥有的适当关联即可。然后试试看。让我知道!有一件事我刚想到。您是否运行了:RAILS\u ENV=test rake db:migrate
?可能是您的测试数据库在区域表中没有城市id
。请测试一下,让我知道!尝试:RAILS\u ENV=testbundle exec RAILS c
,然后尝试在RAILS控制台上创建一个绑定了city
的区域(指向测试数据库)。让我知道。
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
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.