# BDD: How do I create stubs/mocks for chained methods?

**URL:** <https://www.ruby-forum.com/t/bdd-how-do-i-create-stubs-mocks-for-chained-methods/133316>\
**Category:** Rails\
**Created:** [March 30, 2008, 12:25am UTC](https://www.ruby-forum.com/t/bdd-how-do-i-create-stubs-mocks-for-chained-methods/133316 "2008-03-30T00:25:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![eblatt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/7bcc69/32.png) [@eblatt](https://www.ruby-forum.com/u/eblatt)\
**Post date:** [March 30, 2008, 12:25am UTC](https://www.ruby-forum.com/t/bdd-how-do-i-create-stubs-mocks-for-chained-methods/133316/1 "2008-03-30T00:25:50Z")

</div>

I’m a little confused about how to use BDD. Let’s say I have a nested  
(has\_many) relationship using an example we are all familiar with.  
#Models:  
class Post  
has\_many :comments  
end  
class Comment

belongs\_to :post  
end  
Now, assuming the RESTful pattern, I have a before filter get the  
current user and to pick up the nesting @post.

#Controller  
class CommentsController  
before\_filter :login\_required #set current\_user  
before\_filter: get\_post #set @post  
[… the usual rest scaffold stuff …]  
def index  
@comments = @post.comments.find(:conditions =\> ['user\_id = ? ',  
current\_user ] )  
end  
private  
def get\_post  
@post = Post.find(params[:post\_id])  
end  
end

#The Problem  
Because of the ActiveRecord association, @post receives the message  
(:comments)

I can express this rspec expectation like this:  
@post = posts(:posts\_001) #a mock post object from fixtures  
@comment = comments(:comment\_001) # a mock comment from fixtures  
@post.stub!(:comments).and\_return([@comment]) #stub @post.comments to  
return array of containing one comment.

…so far, so good.

Here’s where I get stuck. I want to create an expectation for the  
find() method that I call on the ActiveRecord result set?

I want to set an expectation for this line of code:

@comments = @post.comments.find(:conditions =\> ['user\_id = ? ',  
current\_user ] )

My thought was that I could do the following:

Comment.stub!(:find).and\_return( [@comments] )

But, this does not work, so I’m very confused. I’d appreciate any  
insight that you’d be willing to share.

---

<div class="post-metadata">

**Author:** ![eblatt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/7bcc69/32.png) [@eblatt](https://www.ruby-forum.com/u/eblatt)\
**Post date:** [March 30, 2008, 8:30am UTC](https://www.ruby-forum.com/t/bdd-how-do-i-create-stubs-mocks-for-chained-methods/133316/2 "2008-03-30T08:30:38Z")

</div>

Your find mock does not have the parameters that’s the problem. In  
mocha u would say foo expects find with parameters.

[Http://www.rubyplus.org](Http://www.rubyplus.org)  
Free Ruby & Rails screencasts

On Mar 29, 2008, at 4:25 PM, Elliott B.  
\<removed\_email\_address@domain.invalid
