控制器测试Rspec-用户登录后未经授权的请求-预期响应具有成功状态码(2xx),但是为401

时间:2019-03-29 19:34:19

标签: ruby-on-rails testing devise ruby-on-rails-5 rspec-rails

我在用户登录后收到未经授权的请求(在:index上获取请求)。这是一个简单的用户测试示例,我看不到我在做什么错。

在控制器中current_user存在并已登录,但是请求未经授权。为什么会这样?

module ControllerMacros

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryBot.create(:user, company: FactoryBot.create(:company))
      sign_in user
    end
  end

end

rspec_helper.rb:

require 'spec_helper'
require 'devise'
require 'support/controller_macros'

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.extend ControllerMacros, type: :controller
end

用户测试:

require 'rails_helper'

RSpec.describe Api::V1::UsersController do
  include Devise::Test::ControllerHelpers

  describe "GET /api/v1/users" do
    login_user

    it "should get list of users" do
      get 'index'
      expect(response).to have_http_status(:success)
    end

  end
end

此测试通过并正常工作:

   it "should have a current_user" do
      expect(subject.current_user).to_not eq(nil)
    end

    it "should be signed in" do
      expect(subject.user_signed_in?).to be true
    end

0 个答案:

没有答案