[rspec-users] Mocking a Model Class and a View with RSpec-Rails

Shea Levy shea at shealevy.com
Tue Dec 7 23:40:42 EST 2010



Hi all, 

I'm new to RSpec and to TDD/Agile methods in general (by "new"
I mean I'm about 4/5 of the way through _The RSpec Book_ and haven't yet
actually implemented the practices in my projects), so this question may
seem silly. Suppose I'm using specs to drive the development of a Users
controller, but I haven't implemented the User model yet, or I want to keep
the spec isolated from the model class as much as possible. Is there any
way to modify the following spec file to "mock" out the entire User class
both in the spec AND for the controller? Similarly, suppose I haven't
implemented a view for users/create (and I'm being unconventional in having
a create view instead of a redirect to index) or I just want to keep the
controller spec isolated from work done on the views. Is there anyway to
modify what follows to "mock" out a view for the controller to render? I
view the purpose of a controller as being in charge of sending and
receiving messages to and from all of the other aspects of the application,
so I just want to test the sending and receiving without worrying about
what's on the other end of the communication.


spec/controllers/users_controller_spec.rb: 

require 'spec_helper'

describe UsersController do
 describe "POST create" do
 it "creates a new
user" do
 User.should_receive(:new).with("name" => "Shea Levy")
 post
:create, :user => { "name" => "Shea Levy"}
 end
 end
 end


app/controllers/users_controller.rb: 

def create

User.new(params[:user])
 end  

Cheers,
 Shea Levy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20101207/b1d71598/attachment.html>


More information about the rspec-users mailing list