# Rspc & stubbing out chained methods

**URL:** <https://www.ruby-forum.com/t/rspc-stubbing-out-chained-methods/144814>\
**Category:** Rails\
**Created:** [August 2, 2008, 3:26pm UTC](https://www.ruby-forum.com/t/rspc-stubbing-out-chained-methods/144814 "2008-08-02T15:26:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ratcheer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/aca169/32.png) [@ratcheer](https://www.ruby-forum.com/u/ratcheer)\
**Post date:** [August 2, 2008, 3:26pm UTC](https://www.ruby-forum.com/t/rspc-stubbing-out-chained-methods/144814/1 "2008-08-02T15:26:32Z")

</div>

I’ve just started reading up on Rspec and am trying to write a few specs  
to test methods in my models.  
Consider the following  
class Users  
has\_many :items

def state\_of\_last\_item?  
case items.active.last.state #uses a named scope  
when 0  
# do something  
when 1  
# do something  
when 2  
# do something  
end  
end  
end

I want to write the spec to test that the ‘do somethings’ are working as  
expected. How do I stub out the bit with the named scope? I thought it  
would be something like:  
@user.stub!(‘items.active.last.state’).and\_return(0)  
but this doesn’t work. What is the correct way to stub out something  
like this?  
Thanks  
TC

---

<div class="post-metadata">

**Author:** ![ratcheer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/aca169/32.png) [@ratcheer](https://www.ruby-forum.com/u/ratcheer)\
**Post date:** [August 2, 2008, 5:39pm UTC](https://www.ruby-forum.com/t/rspc-stubbing-out-chained-methods/144814/2 "2008-08-02T17:39:40Z")

</div>

You need a stub for each link in the chain, so to speak. You can do it  
all  
inline

@user = stub(“user”, :items =\> stub(“items”, :active =\> stub(“active”,  
:last  
=\> stub(“last”, :state =\> 0))))

or you can create stubs first and then use them together.

last = stub(“last”, :state =\> 0)  
active = stub(“active”, :last =\> last)  
items = stub(“items”, :active =\> active)  
@user = stub(“user”, :items =\> items)

Regards,  
Craig

---

<div class="post-metadata">

**Author:** ![ratcheer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/aca169/32.png) [@ratcheer](https://www.ruby-forum.com/u/ratcheer)\
**Post date:** [August 3, 2008, 10:05pm UTC](https://www.ruby-forum.com/t/rspc-stubbing-out-chained-methods/144814/3 "2008-08-03T22:05:34Z")

</div>

Thanks for that.  
I was hoping that there would be a way to do it without stubbing out  
each link.
