0

I trying to test a polymorphic association.

I am using RSpec 3.0.2 and shoulda-matchers 2.6.2. My Rails version is: 4.1.4 and Ruby 2.1.2

My First Model: app/models/address.rb

class Address < ActiveRecord::Base
    belongs_to :addressable, polymorphic: true
end

My Second Model: app/models/user.rb

class User < ActiveRecord::Base
    has_many :addresses, as: :addressable
end

My third model: app/models/company.rb

class Company < ActiveRecord::Base
     has_many :addresses, as: :addressable
end

For Address table, I have this migration:

class CreateAddresses < ActiveRecord::Migration
    def change
        create_table :addresses do |t|
            t.string :description
            t.references :addressable, polymorphic: true
            t.timestamps
        end
    end
end

And for my first specification, I have: spec/models/address_spec.rb

require 'rails_helper'

RSpec.describe Address, :type => :model do
    it { should belong_to :addressable }
end

But when I try to run the specification I have this error:

Failures:

1) Address should belong to addressable Failure/Error: it { should belong_to :addressable } Expected Address to have a belongs_to association called addressable (Address does not have a addressable_id foreign key.) # ./spec/models/address_spec.rb:4:in `block (2 levels) in '

enter image description here

Generated table by migration:

enter image description here

Can You please help me identifying where I am missing. I just looked from google coming to stackoverflow, but not solution.

WeezHard
  • 1,982
  • 1
  • 16
  • 37

1 Answers1

2

The addressable_id column is not in your test database. Run:

bundle exec rake db:test:clone

to sync your database changes to your test database.

infused
  • 24,000
  • 13
  • 68
  • 78
  • Thanks.. it works... you saved my day. But running this command I get this warning: `WARNING: db:test:clone is deprecated. The Rails test helper now maintains your test schema automatically, see the release notes for details.` – WeezHard Aug 19 '14 at 18:30
  • @PSantos, http://stackoverflow.com/questions/23351783/when-i-ran-bundle-exec-rake-testprepare-it-errored-out-but-bundle-exec-rake will show you how to update your spec_helper so that Rails will maintain your test schema. – infused Aug 19 '14 at 18:34
  • Hi @infused, this does not help because in my spec/rails_helper.rb (generated by rails g rspec:install) I just have this line: `ActiveRecord::Migration.maintain_test_schema!` But the schema was not updated automatically – WeezHard Aug 19 '14 at 18:44
  • 1
    @PSantos, you should open a separate question about `ActiveRecord::Migration.maintain_test_schema!` not working. – infused Aug 19 '14 at 19:31