## Comments

# I am trying to create a functional test for my tickets_controller#create action.
# I have a curl command at the bottom which sends an API token as an HTTP header and gets a successful response.
# However when I try to set the same header in the ActionController::TestCase the test always fails with a 401 unauthorized
# due to failing this method in the api_controller: authenticate_or_request_with_http_token
# I haven't figured out why curl is able to pass this header appropriately but the test is not.
# Anyone have an idea what I'm getting wrong? Thanks!


## test/functional/tickets_controller_test.rb

require 'test_helper'

class TicketsControllerTest < ActionController::TestCase
def setup
@controller = Api::V1::TicketsController.new
@request.env['Accept'] = 'application/json'
@request.env['Content-type'] = 'application/json'
@request.env['Authorization'] = 'Token token=\"ABCDEF0123456789\"'
# @request.env['HTTP_AUTHORIZATION'] = "Token token=\"ABCDEF0123456789\""
# @request.env['X-HTTP_AUTHORIZATION'] = "Token token=\"ABCDEF0123456789\""
# @request.env['X_HTTP_AUTHORIZATION'] = "Token token=\"ABCDEF0123456789\""
# @request.env['REDIRECT_X_HTTP_AUTHORIZATION'] = "Token token=\"ABCDEF0123456789\""
# @request.env['HTTP_AUTHORIZATION'] = "Token token=\"ABCDEF0123456789\""
end

def test_successfully_create_ticket
parameters = {location: 'testlocation'}
post(:create, parameters)
assert_response :created
assert_equal '{"ticket_id":"5736282738"}', @response.body
end
end

## app/controllers/api/v1/api_controller.rb

class Api::V1::ApiController < ApplicationController
respond_to :json

before_filter :restrict_access

private

def restrict_access
authenticate_or_request_with_http_token do |token, options|
token == 'ABCDEF0123456789'
end
end
end

## app/controllers/api/v1/tickets_controller.rb

class Api::V1::TicketsController < Api::V1::ApiController
respond_to :json

def create
if params[:location_id]
render json: '{"ticket_id":"5736282738"}', status: :created
else
render json: '{"error":"Could not create ticket becase..."}', status: :unprocessable_entity
end
end
end

## A curl command which works for testing creating a ticket

curl -X POST -H "Accept: application/json" -H "Content-type: application/json" -H "Authorization: Token token=\"ABCDEF0123456789\"" http://localhost:3000/api/v1/tickets -d "{\"location_id\":\"location4\"}"

Successful Result: HTTP 201

{"ticket_id":"5736282738"}