How do I get shoulda to recognise my polymorphic a

2019-03-02 15:24发布

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条回答
姐就是有狂的资本
2楼-- · 2019-03-02 15:54

Run migrations on your test database!

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

(the tick should got to Peter Alfvin)

查看更多
登录 后发表回答