Search code examples
ruby-on-railsrspec-rails

rspec fails where 'current_user' code written in controller


I have started rspec coding recently and i am new to rails framework, rspec fails where i am using 'current_user' in controller. Please check below for my controller and rspec code. Thanks in advance.

Controller code:

def task
  @tasks = current_user.alerts.where(kind: "TASK")
end

rspec code:

describe "get #task" do
  it "assigns a task" do            
    sign_in(@user)
    get :task       
    expect(response).to have_http_status(200)       
  end

Solution

  • You can do it like this:

    @request.env["devise.mapping"] = Devise.mappings[:user]
     user = FactoryGirl.create(:user) # Don't forget to create a factory for user
     user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
     sign_in user
    

    It is better to put it in support/devise.rb:

    module ControllerMacros
      def login_user
        before(:each) do
          @request.env["devise.mapping"] = Devise.mappings[:user]
          user = FactoryGirl.create(:user)
          user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
          sign_in user
        end
      end
    end
    
    RSpec.configure do |config|
      config.include Devise::TestHelpers, :type => :controller
      config.extend ControllerMacros, :type => :controller
    end
    

    you can say login_user instead of sign_in(@user)