How do I simulate a login with RSpec?

前端 未结 4 1803
悲哀的现实
悲哀的现实 2020-12-08 02:27

I have been playing with Rails for a couple of years now and have produced a couple of passable apps that are in production. I\'ve always avoided doing any testing though an

4条回答
  •  心在旅途
    2020-12-08 03:04

    As I couldn't make @Brandan's answer work, but based on it and on this post, I've came to this solution:

    # spec/support/rails_helper.rb
    Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } # Add this at top of file
    
    ...
    
    include ControllerMacros # Add at bottom of file
    

    And

    # spec/support/controller_macros.rb
    module ControllerMacros
    
      def login_as_admin
        admin = FactoryGirl.create(:user_admin)
        login_as(admin)
      end
    
      def login_as(user)
        request.session[:user_id] = user.id
      end
    
    end
    

    Then on your tests you can use:

    it "works" do
      login_as(FactoryGirl.create(:user))
      expect(request.session[:user_id]).not_to be_nil
    end
    

提交回复
热议问题