How do I get shoulda to recognise my polymorphic association

南楼画角 提交于 2019-12-02 11:29:51

问题


An almost indentical question to this has been asked before (How to use shoulda matchers to test a polymorphic assoication?) but there was no definitive answer that helps me, so I am trying again.

I am using shoulda to test my associations and the following test fails

require 'spec_helper'

describe LabourEpidural do
  before {@treatment = FactoryGirl.build :treatment}
  subject {@treatment}
  it{should have_many :complications}
end

This fails with the following message

Failure/Error: it{should have_many :complications}
   Expected Treatment to have a has_many association called complications (Complication does not have a complicatable_id foreign key.)

The problem is that my Complication table does have a complicatable_id column. Here are the relevant parts of my models;

class Treatment < ActiveRecord::Base
  has_many :complications, as: :complicatable, dependent: :destroy
end

class Complication < ActiveRecord::Base
  belongs_to :complicatable, polymorphic: true
end

and from my schema.rb;

create_table "complications", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "complicatable_id"
  t.string   "complicatable_type"
end

As far as I can tell everything is in place for the shoulda test to pass, so why isn't it? Shoulda matchers are supposed to 'just work' with polymorphic associations. If I go into the console I can easily create treatments with complications. Any ideas?


回答1:


Run migrations on your test database!

...a mistake I have been caught by many times.

(the tick should got to Peter Alfvin)



来源:https://stackoverflow.com/questions/18405058/how-do-i-get-shoulda-to-recognise-my-polymorphic-association

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