Skip Rails http_basic_authenticate_with in RSpec Test

I am working on MVP (minimum viable product). To offer an easier way to protect admin pages, I just added http_basic_authenticate_with to my AdminController.

The problem is that when I want to test my AdminController, I get "unauthorized" (401) for not logging in.

In this case, it does not make sense to check the authentication - it is just temporary, and as soon as I move to the next sprint, it will be deleted - so I try to skip it in RSpec.

The problem is that I tried many ways and nobody seems to work.

For example, I tried changing http_basic_authenticate_with to avoid authentication. Like this:

require 'spec_helper' module ActionController module HttpAuthentication module Basic def http_basic_authenticate_with(*args) end end end end describe Admin::SubscribersController do describe "GET 'index'" do it "should be OK" do get 'index' response.should be_successful end end end 

But when I run it, it still returns false for this simple test.

Btw, to simplify this test, I just have an action with an empty index on my AdminController and an empty view (index.html.erb).

+4
source share
4 answers

Finally, I started to work.

Something as stated in the docs doesn't work for me:

 get 'index', nil, 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials("admin", "password") 

So, I tried using the "old" approach, which should set request.env ['HTTP_AUTHORIZATION'] :

 request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials("admin","password") 

None of the other solutions worked, so I will just support this with this.

Thanks.

+4
source

If it is normal to skip authentication for all tests for the controller, here is the method that I use in the current project.

 unless Rails.env.test? http_basic_authenticate_with name: "slothbear", password: "kuniklo" end 
+3
source

You can or should even test authentication. Record the test for the unauthenticated (it is now) and authenticated. See Testing HTTP Basic Auth in Rails 2.2+ , this should help.

0
source

In Rails 5.x, this works:

 allow(subject).to receive(:authenticate_or_request_with_http_basic) .with(anything).and_return true 

In Rails 6.x, this works:

 allow(subject).to receive(:http_basic_authenticate_or_request_with) .with(anything).and_return true 

This is because http_basic_authenticate_with is a class level method that adds before_action which actually calls one of these two methods.

You can see which one to use by checking http_authentication.rb here for Rails 6 or here for Rails 5

0
source

All Articles