无法测试应该是belongs_to,在Rails上缺少id外键
您好我一直在寻找一种测试模型关系的方法,并偶然发现应该是gem
- 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 '
虽然我的关系有问题,但我已经测试了在rails console
成功创建了一个与城市绑定的区域。 我肯定错过了什么!!
编辑模型和迁移
class Region < ActiveRecord::Base belongs_to :city end class City 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
属于一个City
,它期望Region
Model中的city_id
foreign_key。
通过迁移在Region
模型中添加city_id
列,然后此测试将起作用! 我认为,这里的shoulda
gem并没有错。 这只是您当前的型号设置。
- 来自Hartl教程的bundle exec rspec spec / requests / static_pages_spec.rb无效
- 重新加载不在rspec中工作的对象
- 在RSpec请求规范中使用Capybara时,设置自定义请求标头的最佳方法是什么?
- 嵌套模型测试:找不到表’*’错误。
- rake db:test:load,undefined方法`’为nil:NilClass
- 在RSTP中接收PUT的错误,但不是POST
- 如何“以编程方式”“迭代地”将每个类对象属性设置为一个值?
- 如何在rails中使用ActiveStorage正确进行模型测试?
- 用于测试DELETE请求的Rspec类似代码给出了不同的结果