如何让shoulda识别我的多态关联

时间:2013-08-23 14:16:12

标签: ruby-on-rails rspec polymorphic-associations shoulda

之前已经问过一个几乎同心的问题(How to use shoulda matchers to test a polymorphic assoication?),但没有明确的答案可以帮助我,所以我再试一次。

我正在使用shoulda来测试我的关联,以下测试失败

require 'spec_helper'

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

此操作失败并显示以下消息

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

问题是我的Complication表确实有一个complicatable_id列。以下是我的模型的相关部分;

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

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

和我的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

据我所知,一切都是为了通过,所以为什么不呢?应该匹配的匹配器应该“正常工作”。如果我进入控制台,我可以轻松创建并发症的治疗方法。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

在测试数据库上运行迁移!

......我多次被抓到的错误。

(应该给Peter Alfvin打勾)