Is it legal to stub the #class method of a Mock object when using RSpec in a Ruby on Rails applicati

Posted by MiniQuark on Stack Overflow See other posts from Stack Overflow or by MiniQuark
Published on 2009-04-19T13:42:46Z Indexed on 2010/04/17 11:03 UTC
Read the original article Hit count: 390

Filed under:
|
|
|
|

I would like to stub the #class method of a mock object:

describe Letter do
  before(:each) do
    @john = mock("John")
    @john.stub!(:id).and_return(5)
    @john.stub!(:class).and_return(Person)  # is this ok?
    @john.stub!(:name).and_return("John F.")
    Person.stub!(:find).and_return(@john)
  end
  it.should "have a valid #to field" do
    letter = Letter.create!(:to=>@john, :content => "Hello John")
    letter.to_type.should == @john.class.name
    letter.to_id.should == @john.id
  end
  [...]
end

On line 5 of this program, I stub the #class method, in order to allow things like @john.class.name. Is this the right way to go? Will there be any bad side effect?

Edit:

The Letter class looks like this:

class Letter < ActiveRecord::Base
    belongs_to :to, :polymorphic => true
    [...]
end

I wonder whether ActiveRecord gets the :to field's class name with to.class.name or by some other means. Maybe this is what the class_name method is ActiveRecord::Base is for?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about rspec