ruby-on-rails - 如何从 RSpec 测试中测试登录操作?
问题描述
我们需要测试应用程序的访问控制方法,以确保只有具有正确角色的用户才能执行某些操作。我们通过在会话中查看谁登录来确定用户的角色。
我们的测试试图改变用户的角色,并确保该角色应该不允许的操作实际上是不允许的。但是,测试不起作用,因为在当前版本的 Rails 中,无法在功能规范中设置会话变量。
我们需要一种方法在测试中填充会话变量,以使我们的授权方法按预期工作,如果失败,我们可以使用解决方法。我们如何填充会话变量或绕过它来测试应用程序中的授权?
这是授权文件中的代码,用于测试用户是否已登录(测试中的多个操作会调用该代码):
def user_logged_in?
!session[:user].nil?
end
spec/rails_helper.rb中的代码会在用户被存根时尝试填充会话变量:
def stub_current_user(current_user, current_role_name = 'Student', current_role)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(current_user)
allow_any_instance_of(ApplicationController).to receive(:current_role_name).and_return(current_role_name)
allow_any_instance_of(ApplicationController).to receive(:current_role).and_return(current_role)
session[:user] = current_user
end
这会导致出现以下错误:
<RSpec::ExampleGroups::AirbrakeExpectionErrors:0x000000138599a0> 的未定义局部变量或方法“会话”
解决方案
推荐阅读
- html - Twitter Bootstrap 视频漂浮在 Main
- time-complexity - 以下问题的时间复杂度是多少?谁能解释一下?
- kubernetes - 创建金丝雀资源时,Flagger 不显示任何日志,并且金丝雀资源似乎不起作用
- react-native - 使用反应原生数组排序功能按财政月份从 4 月到 3 月对数组进行排序
- python - 如何在列表中添加附加字典的每个并行进程的时间戳?
- javascript - 如何在下载中保存 CSV 文件 React / Spring Boot
- mysql - View 不断生成多个不需要的行
- android - 如何将 DataBinding 与 AndroidX 片段一起使用
- node.js - 无法从 BOX SDK 访问文件
- node.js - 错误:在 TCPConnectWrap.afterConnect 处连接 ETIMEDOUT 127.0.0.1:3000 [as oncomplete]