nebulab / simple_command

A simple, standardized way to build and use Service Objects (aka Commands) in Ruby
http://nebulab.it
MIT License
624 stars 55 forks source link

LoadError: Unable to autoload constant [command] #9

Closed janwerkhoven closed 5 years ago

janwerkhoven commented 6 years ago

I've followed this tutorial for JSON Web Tokens and things Simple Command work beautifully until I hit the tests. In the tests the commands each time AuthorizeApiRequest is called I get this error: LoadError: Unable to autoload constant AuthorizeApiRequest.

# app/commands/authorize_api_request.rb

class AuthorizeApiRequest
  prepend SimpleCommand

  def initialize(headers = {})
    @headers = headers
  end

  def call
    user
  end

  private

  attr_reader :headers

  def user
    @user ||= User.find(decoded_auth_token[:user_id]) if decoded_auth_token
    @user || errors.add(:token, 'Invalid token') && nil
  end

  def decoded_auth_token
    @decoded_auth_token ||= JsonWebToken.decode(http_auth_header)
  end

  def http_auth_header
    if headers['Authorization'].present?
      return headers['Authorization'].split(' ').last
    else
      errors.add(:token, 'Missing token')
    end
    nil
  end
end
# app/controllers/admin/authenticated_controller.rb

module Admin
  class AuthenticatedController < ApplicationController

    prepend SimpleCommand

    before_action :authenticate_request

    attr_reader :current_user

    private

    def authenticate_request
      @current_user = AuthorizeApiRequest.call(request.headers).result
      render json: { error: 'Not Authorized' }, status: 401 unless @current_user
    end

  end
end

Am I missing something here? Does one need to do something extra to use Simple Commands in tests?

rodolfobandeira commented 6 years ago

@janwerkhoven Did you notice that authorize_api_requests.rb is named using plural instead of singular? Try renaming to authorize_api_request.rb

janwerkhoven commented 6 years ago

Apologies, that's a typo. I've verified and the file name is app/commands/authorize_api_request.rb as described in this tutorial: https://www.pluralsight.com/guides/ruby-ruby-on-rails/token-based-authentication-with-ruby-on-rails-5-api

It works beautifully when curling to localhost:3000, but breaks in tests... Any suggestions?

rodolfobandeira commented 6 years ago

@janwerkhoven From what I can see in these two examples you showed, looks like you added an additional folder called admin/ and some controllers inside it. Keep in mind that this will could change the namespace behavior for these classes.

Double check if your failing test is on the same path. ex: test/controllers/admin/your_test_file

A full stacktrace or at least the code line its calling that command reference would help to solve this issue. cheers

kennyadsl commented 5 years ago

Closing since too much time passed (sorry), feel free to reopen if this is still a thing.