期望响应具有成功状态代码(2xx),但是为401

时间:2019-03-28 16:39:11

标签: ruby-on-rails rspec devise

在控制器中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

错误:

失败/错误:expect(response).to have_http_status(:success)

此测试通过并正常工作:

   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

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

require 'rails_helper'

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

  describe "GET /api/v1/users" do
    it "should get list of users" do
      login_user
      get 'index'
      expect(response).to have_http_status(:success)
    end

  end
end