我在用户登录后收到未经授权的请求(在: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