views:

66

answers:

2

I'm trying to stub out a method on my current_user (using a modified restful_authentication auth solution) with rspec. I'm completely unsure of how I can access this method in my controller specs. current_user by itself doesn't work. Do I need to get the controller itself first? How do I do this?

Using rails 2.3.5, rspec 1.3.0 and rspec-rails 1.3.2

# my_controller_spec.rb
require 'spec_helper'

describe MyController do

  let(:foos){ # some array of foos }

  it "fetches foos of current user" do
    current_user.should_receive(:foos).and_return(foos)
    get :show
  end
end

Produces

NoMethodError in 'ChallengesController fetches foos of current user'
undefined method `current_user' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1::Subclass_1::Subclass_2::Subclass_2:0x7194b2f4>
A: 

I'm not entirely familiar with restful_authentication, just Authlogic and Devise, but it's probably similar in that current_user is a controller method and not an object, which is why calling should_receive on it isn't working as expected (you're setting an expectation on the object that current_user returns, but the method isn't accessible inside the scope of your expectation).

Try this:

stub!(:current_user).and_return(foos)

rspeicher
i couldn't get it t owork with just stub() I needed controller.stub as mentioned above
brad
+1  A: 

rspec-rails gives you a controller method for use in controller examples. So:

controller.stub!(:current_user).with(:foos).and_return(foos)

ought to work.

zetetic
awesome, i'll test this out, btw, what's the difference between `stub` and `stub!`
brad
None - `stub` is an alias for `stub!`, so they are interchangeable
zetetic
worked! thx a bunch
brad