ruby-on-rails 定义当前用户的Rails控制器测试

iq0todco  于 2023-03-20  发布在  Ruby
关注(0)|答案(1)|浏览(150)

在Rails 7中进行测试时遇到了一个小问题(API模式)。我尝试在测试中手动设置当前用户,这样,当服务器解析路由/方法和控制器时,它会检查验证,这在测试环境中被跳过,然后返回它应该返回的内容。不幸的是,当前用户不知何故被重置,我不确定原因和位置。在到达控制器之前,我没有调用其他方法。

require 'test_helper'
class ThingControllerTest < ActionDispatch::IntegrationTest

  test "call method my_method" do
    me = users(:me)
    User.current = me
    get("/api/users/#{me.id}/do-the-thing")
    assert_response :success
  end

end
class ApplicationController < ActionController::Base

  before_action do |c|
    authenticate_user
  end

  def authenticate_user
    return User.current if Rails.env.test?
    # lots of stuff going on otherwise
  end

end
class ThingController < ApplicationController
  # GET /users/:id/do-the-thing
  def the_thing
    user = User.find(params[:id])
    if (User.current != user) # User.current is nil here
      render json: {}, status: 500
      return
    end
    render json: {}, status: 200
  end

end

我试着手动设置当前用户,但似乎当它到达authenticate_user时,User.current已经为零。谢谢!

igetnqfo

igetnqfo1#

找到了一个变通方法,我为我的控制器测试创建了一个AuthHelper模块,这样我的ApplicationController::authenticate_user就不再有Rails环境中的奇怪情况了。

# test/test_helpers/auth_helper.rb
module AuthHelper

  def headers_jwt_auth(user)
    iat = Time.now
    exp = iat + 4.hours
    payload = {iat: iat.to_i, exp: exp.to_i, some_other_stuff: nil}
    secret = Rails.application.credentials.jwt_secret
    return { Authorization: JWT.encode(payload, secret, 'HS256') }   
  end

end

以及

#  test/controllers/thing_controller_test.rb
require 'test_helper'
require "test_helpers/auth_helper"

class ThingControllerTest < ActionDispatch::IntegrationTest

  include AuthHelper
  
  test "call method my_method" do
    me = users(:me)
    User.current = me
    get("/api/users/#{me.id}/do-the-thing",  headers: headers_jwt_auth(User.current))
    assert_response :success
  end

end

相关问题