Unable to test should belong_to, missing id foreign key on Rails

爱⌒轻易说出口 提交于 2019-12-22 12:04:27

问题


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

  • shoulda (3.5.0)
  • shoulda-context (1.2.1)
  • shoulda-matchers (2.8.0)

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

and I always get a message of

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)>'

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!!

Edit Models and migration

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"

回答1:


Region does not have a 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.

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.



来源:https://stackoverflow.com/questions/32085421/unable-to-test-should-belong-to-missing-id-foreign-key-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!