3

I have a simple test written to check that users can't post into a controller with before_action :authenticate_user!. The test reads:

context 'when the user is not logged in' do
  it 'returns 401' do
    sign_out user

    post wikis_path(params: wiki)

    expect(response).to have_http_status(401)
  end
end

The output in the console is:

Failure/Error: expect(response).to have_http_status(401)
       expected the response to have status code 401 but it was 302

But when I check the test log it does shows 401:

Processing by WikisController#create as HTML
  Parameters: {"wiki"=>{"content"=>"Some content"}}
Completed 401 Unauthorized in 4ms (ActiveRecord: 0.0ms)

Moreover, I can open the browser, delete the auth cookie and verify that it does indeed respond with 401.

At first, I thought the redirect was Devise behavior because it says that it is in their comments, however neither the log or the behavior do this. There is a similar (old) question of a user not using Devise, but getting the same result. I'll admit, I can't grok all of the Devise code, but I was able to lookup and follow authenticate_or_request_with_http_token in the Rails code all the way to the end to see that it should have (in his case) returned 401.

What is causing the disagreement between the failing test/output in the console and the logged result in test.log?

1 Answers1

2

In reality, the first status code is 302 (Redirect), then the next is 401. I don't have idea why the test.log doesn't show 302. Below is the script for redirect case (ref: https://relishapp.com/rspec/rspec-rails/docs/matchers/have-http-status-matcher)

context 'when the user is not logged in' do
  it 'returns 401' do
    sign_out user

    post wikis_path(params: wiki)

    expect(response).to have_http_status(302)

    follow_redirect!
    expect(response).to have_http_status(401)
  end
end
Phan Việt
  • 1,253
  • 11
  • 11