Created
January 30, 2016 13:22
-
-
Save abitdodgy/72f2fd904811f713e860 to your computer and use it in GitHub Desktop.
API on Rails example with fake controller and concern.
This file contains hidden or 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
module Authable | |
def current_user | |
@current_user ||= User.find_by(auth_token: request.headers['Authorization']) | |
end | |
def authenticate_with_token! | |
render json: { errors: "Not authenticated" }, status: :unauthorized unless current_user.present? | |
end | |
end |
This file contains hidden or 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
require 'test_helper' | |
class DummyController < ApplicationController | |
include Authable | |
before_action :authenticate_with_token! | |
def index | |
render nothing: true | |
end | |
end | |
class DummyControllerTest < ActionController::TestCase | |
test "#authenticate_with_token! returns an error when no Authorization header is present" do | |
with_routing do |set| | |
set.draw do | |
resources :dummy, only: :index | |
end | |
get :index | |
assert_response :unauthorized | |
assert_equal json_response_body[:errors], "Not authenticated" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment