Mocking a Model Class and a View with RSpec-Rails

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
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
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
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
so I just want to test the sending and receiving without worrying about
what’s on the other end of the communication.


require ‘spec_helper’

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


def create[:user])

Shea Levy

On Dec 7, 2010, at 8:40 PM, Shea Levy wrote:

  User.should_receive(:new).with("name" => "Shea Levy")

Shea Levy

rspec-users mailing list
[email protected]

If you haven’t defined the User class, all you need to do to get your
tests passing is to define a User constant. If I’m working on a
controller and set of views and haven’t made the model yet, I’ll usually
just do

class User; end

in my spec_helper.rb. That way the constant exists and Ruby is happy.
When I’m ready to do the model, I delete that line.

re: mocking out views, controller specs are isolated from their views by
default. Meaning that in the example you posted, the view won’t be
rendered at all. If you want the views to be rendered, you call
integrate_views from within the controller example group.