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

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.

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
Free Ruby & Rails screencasts

On Mar 29, 2008, at 4:25 PM, Elliott B.
<[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs