测试使用令牌登录用户和SimpleTokenAuthentication失败,因为SimpleTokenAuthentication未登录用户

时间:2018-12-19 09:36:22

标签: rspec ruby-on-rails-5.2 http-token-authentication

Rails 5.2 宝石:SimpleTokenAuthentication

我有以下控制器:

class RegistrationsController < ApplicationController
  acts_as_token_authentication_handler_for  User, only: [:start]



  def start
    binding.pry
    if user_signed_in?
      redirect_to edit_user_path(current_user)
    else
      redirect_to new_user_session_path
    end
  end

end

我有一个页面,该页面的链接带有填充有适当数据的user_email和user_token参数。

当我单击链接时,如果令牌有效且电子邮件属于数据库中的用户,则act_as_token_authentication_handler_for用户会登录用户。

但是,当我尝试运行简单的rspec测试时,出现内部服务器错误。

这是Rspec测试:

RSpec.describe 'Registering New Staff' do

  let(:new_user) { create(:user) }

  describe 'accessing the registration start page' do

    it 'redirects to the edit user path when user signed in' do
      params = { user_email: new_user.email, user_token: new_user.authentication_token }
      get start_registration_path(params)
      expect(response).to redirect_to(edit_user_path(new_user))
    end
  end

这是我得到的错误:

  Failure/Error: expect(response).to redirect_to(edit_user_path(new_user))
       Expected response to be a <3XX: redirect>, but was a <500: Internal Server Error>

使用acts_as_token_authentication_handler_for登录过程似乎出了点问题,但我无法弄清楚。

任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

最后,我最终没有使用SimpleTokenAuthentication并使用自己的代码,如下所示:

class RegistrationsController < ApplicationController 
  before_action :authenticate_user_from_token!, only: [:start]

  def preview
  end

  def start
    authorize :registration
    if user_signed_in?
      redirect_to edit_user_path(current_user)
    else
      raise Pundit::NotAuthorizedError
    end
  end

  def calendar
    authorize :registration
  end

  def confirmation
    authorize :registration
    current_user.register
  end


  private

  def authenticate_user_from_token!
    sign_out current_user if user_signed_in?
    if user && Devise.secure_compare(user.authentication_token, params[:user_token])
      sign_in user 
      @current_user = user
      renew_authentication_token
    end
  end

  def user
    @user ||= User.find_by(email: params[:user_email])
  end

  def renew_authentication_token
    current_user.renew_authentication_token!
  end

end