The basic question: how do you mock (or stub) a reference to a
polymorphic class in RSpec? Trying the obvious thing leads to an error
of the form:

undefined method `base_class' for Post:Class

=== The details:

# file: app/models/relation.rb
class Relation < ActiveRecord::Base
belongs_to :entity, :polymorphic => true

# file: db/xxx_create_relations.rb
class CreateRelations < ActiveRecord::Migration
def change
create_table :relations do |t|
t.references :entity, :polymorphic => true, :null => false

# file: spec/models/relation_spec.rb
describe Relation do
it 'should create instance without error' do
post = mock_model("Post")
lambda { Relation.create!(:entity => @post)}.should_not raise_error

=== Running the test:

1) Relation should create instance without error
Failure/Error: lambda { Relation.create!(:entity => post)
}.should_not raise_error
expected no Exception, got #<NoMethodError: undefined method
`base_class' for Post:Class>
# ./spec/models/relation_spec.rb:39:in `block (2 levels) in <top

My hunch is that ActiveRecord is calling base_class on the mocked model
(Post) to determine what to stick in the 'entity_type' column in the
relations table. I tried explicitly setting it, as in:

post = mock_model("Post", :base_class => "Post")

but the error was the same.

For all the reasons that DC espouses, I'd love to mock (or stub)
references to the polymorphic models, but I don't see how to do that.
Any ideas?

Posted via

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 2 | next ›
Discussion Overview
grouprubyonrails-talk @
postedMar 22, '12 at 12:24p
activeMar 29, '12 at 1:01p

2 users in discussion

David Chelimsky: 1 post Fearless Fool: 1 post



site design / logo © 2021 Grokbase