Reputation: 1940
I currently have defined an auth class using grape as below:
module V1
class ApiAuth < Grape::API
resource :auth do
desc "Creates and returns access_token if valid login"
post ...
this class resides in the app/api/v1 directory. My test looks like the following:
class V1::ApiAuthTest < ActiveSupport::TestCase
include Rack::Test::Methods
def app
Rails.application
end
def setup
@candidate = create(:candidate_with_encrypted_password)
end
test 'returns status 201 when logged in' do
...
When I run the test with "rake test test/api/v1/api_auth_test.rb" the test runs fine. However if I run all tests with "rake test" or "rake test test/api/v1/*" I get the following error:
rake aborted!
NameError: uninitialized constant V1
/Users/user/Projects/learning/test/api/v1/api_auth_test.rb:1:in `<top (required)>'
Tasks: TOP => test:run
(See full trace by running task with --trace)
What am I doing wrong, do I have to load the V1 module in the test_helper?
Upvotes: 0
Views: 365
Reputation: 27207
The error message shows that V1
is not defined at the point that Ruby loads the test file. You have to load (or require
) the relevant app code that you are testing, and that require
must run before you can refer V1
directly.
Yes the test helper is usually a good place to do that. You may also need to require
the test helper file from your test if you are not already.
If you are already requiring the app code in order to test it, later, then this can be treated as a simpler problem of the namespace not existing yet. Either define it in the helper:
module V1
end
Or change your test code from the question to fully nest the namespace:
module V1
class ApiAuthTest < ActiveSupport::TestCase
# Etc.
Which approach to take depends on how you want to organise your dependencies. If anything else in the test file which runs at the time it is loaded depends on definitions elsewhere (e.g. Rack::Test::Methods
has to be defined in order to include
it), then it needs to be loaded before the test file references it.
You don't usually need to worry about things defined inside the test
blocks until they are run, so you can often load the test code and then the app code in that order, and everything will work just fine. In this case it could just be the missing namespace that has caused you to need to notice load order of the files.
Upvotes: 1