Skip to content

Instantly share code, notes, and snippets.

@blaze182
Created September 30, 2017 17:39
Show Gist options
  • Save blaze182/3a59a6af8c6a7aaff7bf5f8078a5f2b6 to your computer and use it in GitHub Desktop.
Save blaze182/3a59a6af8c6a7aaff7bf5f8078a5f2b6 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

upd: only tested for Rails 5.0

@xbits
Copy link

xbits commented Mar 1, 2020

signed_in test fails without using "create(:user)" instead of "build"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment