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

Pat Maddox patmaddox at me.com
Wed Dec 8 13:00:13 EST 2010

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

> 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
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

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.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20101208/c8c5d5f7/attachment.html>

More information about the rspec-users mailing list