dimanche 8 mai 2016

Devise Signin Testing with RSpec for API

      authenticate_with_http_token do |token, options|
    auth_key = AuthKey.find_by(authentication_token: token)
    if auth_key.present?
      if auth_key.token_valid?
        auth_key.touch
        sign_in(:user, auth_key.user, store: false, bypass: false) unless current_user.present?
      else
        render json: { message: t('invalid_otp_access'), errors: [t('token_expired')] }, status: 401 and return
      end
    else
      render json: { message: t('invalid_access_message'), errors: [t('invalid_access')] }, status: 401 and return
    end
  end

i need to write spec for the above code, in my controller i am using current_user.

My controller looks like below.

  def index
schedules = params[:type] == "upcoming" ? :upcoming : :past
schedules = current_user.audit_schedules.send(schedules)
if schedules.present?
  paginate json: schedules, per_page:10, root: false, each_serializer: Api::V1::MyAuditSerializer
else
  render json: { message: t('.no_audits_scheduled'), errors: [] }
end
end

and i am trying to test my index with passing valid token and params

context "with invalid attributes" do
  it "It will return list of audits" do
    request.headers["Authorization"] = "Token #{auth_key.authentication_token}"
    @request.env["devise.mapping"] = Devise.mappings[:user]
    get :index, { params: { type: "upcoming" } }
    expect(response.body).to eq 200
  end
end

the above spec returning body like

<html><body>You are being <a href=\"http://ift.tt/1fuvND2\">redirected</a>.</body></html>

And in my spec helper i included devise helpers like

  config.include Devise::TestHelpers, type: :controller

If i remove that helper current_user is always nil. if i add that helper it is redirecting like above, please let me know what i missed and how can i test those spec.

Aucun commentaire:

Enregistrer un commentaire