Devise, undefined local variable or method current_user-Collection of common programming errors

I have Project controller and rspec file for it. I’m usig current_user helper in this way:

# projects_controller_spec.rb

describe "user signed in" do
  before(:each) { sign_in @user }
  after(:each)  { sign_out @user}

  describe "GET index" do      
    it "assigns all projects as @projects" do
      project = FactoryGirl.create(:project, :user => current_user)
      get :index, {}, valid_session
      assigns(:projects).should eq([project])
    end
  end
  ...
end

The helpers sign_in and sign_out seem to work fine but I’v got an error on current_user:

undefined local variable or method `current_user'

What might be a problem, how to fix it?

  1. It’s normal. You should create a User instance. You could use let like this :

    # projects_controller_spec.rb
    
    describe "user signed in" do
    
      let(:user) {FactoryGirl.create(:user)}
      before(:each) { sign_in user }
      after(:each)  { sign_out user}
    
      describe "GET index" do      
        it "assigns all projects as @projects" do
          project = FactoryGirl.create(:project, :user => user)
          get :index, {}, valid_session
          assigns(:projects).should eq([project])
        end
      end
      ...
    end
    

    You know than the current_user is user …

    You don’t need to sign out your use after each spec.

Originally posted 2013-11-09 21:43:07.