[rspec-users] rspec_on_rails, could someone provide an example of using mocks/stubs?

David Green justnothing at tiscali.co.uk
Fri Jun 1 05:00:53 EDT 2007

hi all

I'm still a little uncertain on how to use mocks/stubs with rspec when
dealing with associations. I know the point is to isolate the code being
tested and remove external dependencies, but I'm not sure how to implement
it. Can someone suggest how they would spec the code below:

I have a Book model and Review model

class Book < ActiveRecord::Base
  has_many :reviews

  def update_rating
    new_rating = 0.0
    unless reviews.empty?
      reviews.each {|r| new_rating += r.rating}
      new_rating /= review.size
    update_attribute(:rating, new_rating)


The review class is just a standard model with a :rating attribute. Here's
the (empty) spec i came up with:

describe Book, ".update_rating" do

  it "should set rating to 0.0 when there are no reviews" do

  it "should set :rating to the average rating when there are reviews" do


I know I'm supposed to implement the specs first but I wrote the
update_attribute() method here to show the kinds of method calls it would be
making. Here's what I think I need to do:

- stub @book.reviews to return a mock object e.g. mock_reviews
- stub mock_reviews.each to return another mock e.g. mock_r
- stub mock_r.rating to return some value

am I on the right track? it seems like a lot of preparation for such a
simple test. Is there a better way?

View this message in context: http://www.nabble.com/rspec_on_rails%2C-could-someone-provide-an-example-of-using-mocks-stubs--tf3851161.html#a10909256
Sent from the rspec-users mailing list archive at Nabble.com.

More information about the rspec-users mailing list