[rspec-users] How to mock a logged in user

Raghunandan Somaraju somaraju at gmail.com
Mon Nov 22 07:24:03 EST 2010


I need to update something for a logged in user. My controller code for 
the action is:

def som_action
   @_current_user.save_choice(params)
end

My application_controller.rb contains the following:

class ApplicationController < ActionController::Base
   before_filter :current_user

   def current_user
     @_current_user ||= session[:current_user_id] &&
       User.find(session[:current_user_id])
   end
end

In my controller spec, I am trying something like this:

   let(:user) { mock_model("User", :id => 1001) }
   let(:item) { mock_model("Item", :id => 1010) }

   before(:each) do
     controller.stub!(:current_user).and_return(user)
   end

   describe "POST create" do
     context "when the user chooses an item" do
       it 'creates a item_choice' do
         ItemChoice.should_receive(:new).
           with("requester_id" => user.id, "item_id" => item.id).
           and_return(item_choice)
         post :create, :item_choice => { "item_id" => item.id }
         response.should redirect_to(home_path)
       end
     end
   end


I get nil object error when I run this spec, as there is no 
@_current_user set. How do I stub such that there is a user with an id 
to do this?

raghu


More information about the rspec-users mailing list