Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Request specs devise_token_auth Authentication helpers
# spec/support/requests/auth_helpers.rb
module Requests
module AuthHelpers
module Extensions
def sign_in(user)
let(:auth_helpers_auth_token) {
self.public_send(user).create_new_auth_token
}
end
end
module Includables
HTTP_HELPERS_TO_OVERRIDE =
[:get, :post, :patch, :put, :delete].freeze
# Override helpers for Rails 5.0
# see http://api.rubyonrails.org/v5.0/classes/ActionDispatch/Integration/RequestHelpers.html
HTTP_HELPERS_TO_OVERRIDE.each do |helper|
define_method(helper) do |path, **args|
add_auth_headers(args)
args == {} ? super(path) : super(path, **args)
end
end
private
def add_auth_headers(args)
return unless defined? auth_helpers_auth_token
args[:headers] ||= {}
args[:headers].merge!(auth_helpers_auth_token)
end
end
end
end
# spec/rails_helper.rb
# ...
RSpec.configure do |config|
# ...
# Helpers
config.include Requests::AuthHelpers::Includables, type: :request
config.extend Requests::AuthHelpers::Extensions, type: :request
# ...
end
# Usage example, note lines 9, 12 and 19
# - user should be a valid devise-enabled model factory
require 'rails_helper'
RSpec.describe "Token Validations", type: :request do
describe 'signed in' do
let(:user) { build :user }
sign_in(:user)
it 'should respond with success' do
get '/api/v1/auth/validate_token' # yes, nothing changed here
expect(response).to have_http_status(:success)
end
end
describe 'signed out' do
it 'should respond with unauthorized' do
get '/api/v1/auth/validate_token'
expect(response).to have_http_status(:unauthorized)
end
end
end
@blaze182

This comment has been minimized.

Copy link
Owner Author

commented Sep 30, 2017

Addressing devise_token_auth RSpec testing issue for request specs: lynndylanhurley/devise_token_auth#75

This helper overrides http helpers to implicitly merge in authentication headers if sign_in(:user) was called

@blaze182

This comment has been minimized.

Copy link
Owner Author

commented Sep 30, 2017

upd: only tested for Rails 5.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.