[rspec-users] Stub activerecord find given instance?

Saverio Miroddi lists at ruby-forum.com
Sun Jan 24 18:10:32 EST 2010

David Chelimsky wrote:
> It'd be much easier to help you if you could provide an example more
> representative of what you are actually trying to accomplish.

So, here it is (note: this is NOT representative of a properly 
engineered behavior):

class MyModel
  def my_parent
    self.find( my_parent_id )

class MyController < ...
  def show
    m = MyModel.find( params[ :id ] )
    mp = m.my_parent

    @m_value = m.value
    @mp_value = mp.value

now, suppose I want to stub a behavior only for the child object ('m').
so my intention in the spec is to:

- create the child and his parent
- stub MyModel#value in the child
- stub MyModel.find to return "m" _only_ when called with the child id, 
otherwise it should do its usual business. if I stub generically, 
m#my_parent would return "m" itself.

the test would be:

it "should display a stubbed value for the children" do
  mp = MyModel.create!( :value => 0xCAFEBABE )
  m  = MyModel.create!( :my_parent_id => mp.id, :value => 64738 )

  m.stub!( :value ).with( m.id ).and_return( 42 )

  get :show, :id => m.id

what happens is:
- if I don't use ".with( m.id )", @m_value and @mp_value will have 
m.value assigned.
- if I use ".with( m.id )", I even get an error "undefined method `find' 
for #<Class:0x7f2b3116a2c0>" at the line "self.find( my_parent_id )" 
inside the method MyModel#my_parent.

Hope this clarified, it's not real production code, but it models a 
behavior sometimes I actually needed.

Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list