How do I simulate a login with RSpec?

前端 未结 4 1806
悲哀的现实
悲哀的现实 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

    The answer depends on your authentication implementation. Normally, when a user logs in, you'll set a session variable to remember that user, something like session[:user_id]. Your controllers will check for a login in a before_filter and redirect if no such session variable exists. I assume you're already doing something like this.

    To get this working in your tests, you have to manually insert the user information into the session. Here's part of what we use at work:

    # spec/support/spec_test_helper.rb
    module SpecTestHelper   
      def login_admin
        login(:admin)
      end
    
      def login(user)
        user = User.where(:login => user.to_s).first if user.is_a?(Symbol)
        request.session[:user] = user.id
      end
    
      def current_user
        User.find(request.session[:user])
      end
    end
    
    # spec/spec_helper.rb
    RSpec.configure do |config|
      config.include SpecTestHelper, :type => :controller
    end
    

    Now in any of our controller examples, we can call login(some_user) to simulate logging in as that user.


    I should also mention that it looks like you're doing integration testing in this controller test. As a rule, your controller tests should only be simulating requests to individual controller actions, like:

    it 'should be successful' do
      get :index
      response.should be_success
    end
    

    This specifically tests a single controller action, which is what you want in a set of controller tests. Then you can use Capybara/Cucumber for end-to-end integration testing of forms, views, and controllers.

提交回复
热议问题