0

I'm trying to run the following spec:

describe UsersController, "GET friends" do

  it "should call current_user.friends" do
    user = mock_model(User)
    user.should_receive(:friends)
    UsersController.stub!(:current_user).and_return(user)
    get :friends
  end

end

My controller looks like this

  def friends
    @friends = current_user.friends
    respond_to do |format|
      format.html
    end
  end

The problem is that I cannot stub the current_user method, as when I run the test, I get:

Spec::Mocks::MockExpectationError in 'UsersController GET friends should call current
_user.friends'
Mock "User_1001" expected :friends with (any args) once, but received it 0 times[0m
./spec/controllers/users_controller_spec.rb:44:

current_user is a method from Restful-authentication, which is included in this controller. How am I supposed to test this controller?

Thanks in advance

skaffman
  • 398,947
  • 96
  • 818
  • 769
Thiago
  • 2,238
  • 4
  • 29
  • 42

1 Answers1

1

You will need to mock a user and then pass it into the login_as method to simulate logging in the user.

@user_session = login_as(stub_model(User))
UserSession.stubs(:new).returns(@user_session)

http://bparanj.blogspot.com/2006_12_01_archive.html

Schneems
  • 14,918
  • 9
  • 57
  • 84
  • I've tried:
      it "should call current_user.friends" do
    
        user = mock_model(User)
        user.should_receive(:friends)
        @user_session = login_as(user)
        get :friends
      end
    
    But it also didn't work. I thought that if I only call login_as it would be solved. Why's that?
    – Thiago May 12 '10 at 20:28
  • you may also need to call: UserSession.stubs(:new).returns(@user_session) (or rename UserSession to the session model that restful-authentication created to handle sessions) – Schneems May 12 '10 at 22:22