Rspec for polymorphic classes

Rspec forum has troubles

Does anyone have examples for rspec model for a polymorphic class?

Since attributes get dynamically created into the db, this is different
to test than normal rspec models.

Factory Girl would be great too! Just a simple one will do!

I woiuld like to test the derived class (not the polymorphic class).

I am not sure I understand what you need, can you shows us your classes?
It
will be easier to answer your question if you give us your code maybe in
a
gist?

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

I’m not sure why you can’t write a normal rspec against these objects—
generally rspec tests the objects themselves and how their public
methods are implemented (and, when appropriate, the internals of the
object implementation).

The decision to make the attachment polymorphic – which incidentally
looks like a fine choice in this case – is an implementation decision.

In these cases, I would test

  • That a User can have many (add/remove) addresses
  • That a Company can have many (add/remove) addresses)
  • That an address that belongs to a User can be correctly instantiated
    (and addressable is the user you are expecting)
  • That an address that belongs to a Company can be correctly
    instantiated (and addressable is the company you are expecting)

(Some might argue that the things I listed above are over-kill testing,
since all you’re really doing is testing active record. I generally do
write a few of these style of tests for sanity, but tend to not go
overboard testing every feature of the association interface — those
features provided by AR itself — in my unit tests)

Remember, your rspec will say something like

address.addressable.should eq(user)

The decision to implement as polymorphic is an implementation decision,
so although in your case addressable is a belong_to polymorphic
association, it could easily be implemented as a method on the object
itself. Your unit test should be abstract from that, making your
implementation de-coupled from your test expectation.

-Jason