RSpec控制台日志返回302,但测试日志显示401

时间:2018-02-04 22:14:52

标签: rspec devise

我编写了一个简单的测试来检查用户是否可以使用before_action :authenticate_user!发布到控制器中。测试结果如下:

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

控制台中的输出是:

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

但是当我检查测试日志时,它确实显示了401:

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

此外,我可以打开浏览器,删除auth cookie并验证它确实以401响应。

起初,我认为重定向是Devise行为,因为它说它在their comments,但是日志或行为都没有这样做。有similar (old) question的用户没有使用Devise,但得到的结果相同。我承认,我无法理解所有Devise代码,但我能够在Rails代码中查找并跟踪authenticate_or_request_with_http_token一直到最后看到它应该有(在他的情况下)返回401。

导致控制台中测试/输出失败与test.log中记录结果之间存在分歧的原因是什么?

1 个答案:

答案 0 :(得分:1)

实际上,第一个状态代码是302(重定向),然后下一个是401.我不知道为什么test.log没有显示302.下面是重定向案例的脚本(参考: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