[rspec-users] stubbing controller methods (unstumped)

Jonathan Linowes jonathan at parkerhill.com
Thu May 31 01:53:35 EDT 2007


thanks!!

My confusion was aggravated by a bug in my controller so I thought  
the stub wasn't working when it was. Other problems included things  
like forgetting a "?" on methods like "logged_in?" ...

Writing the test examples like below really helped me sort it out.

I've blogged it at http://www.vaporbase.com/postings/ 
Using_Rspec_on_Controllers

linoj


On May 30, 2007, at 11:19 PM, David Chelimsky wrote:

> On 5/30/07, Jonathan Linowes <jonathan at parkerhill.com> wrote:
>> I must be dense because I keep having trouble stubbing anything in a
>> controller. I can stub models but not controller methods, whether
>> directly defined in the controller file or in a module
>>
>> Here's a small example:
>>
>> # sandbox_controller.rb
>>
>> class SandboxController < ApplicationController
>>    def someaction
>>      @value = somemethod
>>    end
>>
>>    def somemethod
>>      return 10
>>    end
>
> This is an instance method.
>
>> end
>>
>> # sandbox_controller_spec.rb
>>
>> require File.dirname(__FILE__) + '/../spec_helper'
>>
>> describe SandboxController, " handling someaction" do
>>    before do
>>      SandboxController.stub!(:somemethod).and_return(99)
>
> This is stubbing a class method, which doesn't exists. Try this:
>
>     controller.stub!(:somemethod).and_return(99)
>
> Cheers,
> David
>
>>    end
>>
>>    it "should get 99" do
>>      get :someaction
>>      assigns[:value].should equal(99)
>>    end
>> end
>>
>> # console
>>
>> $ script/spec spec/controllers/sandbox_controller_spec.rb --color --
>> format specdoc
>>
>> SandboxController handling someaction
>> - should get 99 (FAILED - 1)
>>
>> 1)
>> 'SandboxController handling someaction should get 99' FAILED
>> expected 99, got 10 (using .equal?)
>> ./spec/controllers/sandbox_controller_spec.rb:10:
>> script/spec:4:
>>
>> Finished in 0.13381 seconds
>>
>> 1 example, 1 failure
>>
>>
>> In real life I want to stub out the authentication methods in  
>> module /
>> lib/authenticated_system.rb , or the before_filter method as
>> suggested to me earlier so I can move forward with my spec'ing
>> controllers that have authorization built in. This is getting  
>> painful.
>>
>> linoj
>>
>>
>>
>> _______________________________________________
>> rspec-users mailing list
>> rspec-users at rubyforge.org
>> http://rubyforge.org/mailman/listinfo/rspec-users
>>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list