mercredi 4 octobre 2017

Writing tests for API token auth controller in Rspec

I am following this tutorial to create token authentication: tutorial

Here is the controller code from the tutorial

Session controller for API:

class Api::SessionsController < Api::BaseController
  skip_before_action :require_login!, only: [:create]

  def create
    resource = User.find_for_database_authentication(email: params[:email])
    resource ||= User.new
    if resource.valid_password?(params[:password])
      auth_token = resource.generate_auth_token
      render json: { auth_token: auth_token }
    else
      invalid_login_attempt
    end
  end

  def destroy
    resource = current_person
    resource.invalidate_auth_token
    head :ok
  end

  private

  def invalid_login_attempt
    render json: { errors: [ { detail: 'Error with your login or password' }]}, status: 401
  end
end

Base controller for API:

class Api::BaseController < ActionController::Base
  before_action :require_login!
  helper_method :person_signed_in?, :current_user

  def user_signed_in?
    current_person.present?
  end

  def require_login!
    return true if authenticate_token
    render json: { errors: [ { detail: 'Access Denied' } ] }, status: 401
  end

  def current_user
    @_current_user ||= authenticate_token
  end

  private

  def authenticate_token
    authenticate_with_http_token do |token, options|
      User.find_by(auth_token: token)
    end
  end
end

How would I go about testing those methods? Specifically, the "create" method, where do I send the params from? Any insight would be great, thanks!

Aucun commentaire:

Enregistrer un commentaire