首页 > 解决方案 > 如何从 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> 的未定义局部变量或方法“会话”

标签: ruby-on-railstestingauthorizationsession-variablesrspec-rails

解决方案


推荐阅读