Skip to content

Instantly share code, notes, and snippets.

@nathanows
Last active November 3, 2022 09:34
Show Gist options
  • Save nathanows/b5346256b06d8ce61f8e to your computer and use it in GitHub Desktop.
Save nathanows/b5346256b06d8ce61f8e to your computer and use it in GitHub Desktop.
RSpec: Testing Token/API Key Authentication
##
## TOKEN/API KEY AUTHENTICATION
## This was based on blogger-advanced
## Continuing from the class we built this in...
## if not already done, you'll need to make an ApiKey table in the DB 'rails g model ApiKey token:string'
##
# app/controllers/api/v1/articles_controller.rb
class Api::V1::ArticlesController < ApplicationController
#...
before_action :authenticate
#...
private
def authenticate
authenticate_or_request_with_http_token do |token, options|
ApiKey.exists?(token: token)
end
end
end
# spec/support/auth_helper.rb
module AuthHelper
def http_login
token = 'SomeRandomToken'
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials(token)
end
end
# spec/spec_helper.rb (or rails_helper.rb, whichever, but in the existing RSpec.configure block include the AuthHelper module)
RSpec.configure do |config|
config.include AuthHelper, :type => :controller
end
# Skipping the Factory girl setup steps (find them here http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md)
# Summary: add 'factory_girl_rails' and 'database_cleaner' gems to your Gemfile
# From the link above, add in the code snippets from the 'Configure your test suite' and 'Linting factories' sections
# spec/factories.rb
FactoryGirl.define do
factory :api_key do
token "SomeRandomToken"
end
factory :author do
name "John Doe"
email "john@example.com"
password "password"
end
factory :article do
title "How to play cards"
body "It's pretty simple really..."
author
end
end
# controller spec (spec/controllers/app/v1)
require 'spec_helper'
RSpec.describe Api::V1::ArticlesController, :type => :controller do
describe "GET index" do
it "responds to json" do
create(:api_key)
create_list(:article, 2)
http_login #this is the method call from the AuthHelper module
get :index, format: 'json'
items = JSON.parse(response.body)
first_item = items.first
expect(response.status).to eq(200)
expect(items.count).to eq(1)
expect(first_item["title"]).to eq("How to play cards")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment