如何检测Ruby on Rails带Devise认证接口的内存泄漏?
解决Derailed Benchmarks无法测试Devise认证接口的问题
问题根源
Derailed的perf:objects命令底层通过curl发送请求,但Devise保护的接口需要携带认证信息才能访问,默认curl请求不带会话或token,会被认证拦截,导致测试失败。
可行解决方案
1. 携带Cookie会话发起请求
- 先在浏览器登录你的Rails应用,从开发者工具的存储/Application标签中复制Devise的会话Cookie(格式通常为
_<你的应用名称>_session)。 - 在Derailed命令中通过
-H参数添加Cookie请求头:bundle exec derailed exec perf:objects -H "Cookie: _your_app_session=复制的Cookie值" /your-authenticated-endpoint
2. 使用Token认证(若启用Devise Token Auth)
如果你的应用集成了Devise Token Auth模块,直接在请求头中携带token和用户邮箱:
bundle exec derailed exec perf:objects -H "Authorization: Token token=测试用户的token, email=user@example.com" /your-authenticated-endpoint
3. 测试环境临时跳过认证(快速测试用)
在测试环境下,给目标控制器临时添加跳过认证的逻辑,测试完成后记得移除:
# 在目标控制器中添加 skip_before_action :authenticate_user!, only: [:要测试的接口动作] if Rails.env.test?
之后直接运行原命令即可:
bundle exec derailed exec perf:objects /your-authenticated-endpoint
4. 自定义Derailed请求逻辑(进阶方案)
如果需要自动完成登录流程,可以修改Derailed的perf:objects任务:
- 找到Derailed任务文件
lib/derailed_tasks/perf/objects.rb - 在发起目标接口请求前,先通过curl调用登录接口保存Cookie,再携带Cookie访问目标接口,示例代码片段:
# 先执行登录请求并保存Cookie `curl -c ./devise_cookies -d "user[email]=test@example.com&user[password]=测试用户密码" #{Rails.root}/users/sign_in` # 携带Cookie发起目标接口请求 curl_cmd = "curl -b ./devise_cookies #{target_url}"
注意事项
- Cookie存在过期时间,若测试中途出现认证失败,重新获取最新Cookie即可。
- 临时跳过认证的方法仅限测试环境使用,禁止在生产环境操作。
- 使用Token认证时,需确保测试用户的token有效且拥有对应接口的访问权限。
内容的提问来源于stack exchange,提问作者Bala
相关产品推荐
相关产品推荐

