Created
September 30, 2017 17:39
-
-
Save blaze182/3a59a6af8c6a7aaff7bf5f8078a5f2b6 to your computer and use it in GitHub Desktop.
Request specs devise_token_auth Authentication helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/rails_helper.rb | |
# ... | |
RSpec.configure do |config| | |
# ... | |
# Helpers | |
config.include Requests::AuthHelpers::Includables, type: :request | |
config.extend Requests::AuthHelpers::Extensions, type: :request | |
# ... | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
signed_in test fails without using "create(:user)" instead of "build"