You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用RSpec测试AdminController中的当前用户相关逻辑

RSpec 测试 AdminController 当前用户逻辑实现

场景覆盖说明

我们需要针对两个方法的所有逻辑分支做全量覆盖测试:

  • current_account:session存有效ID、session无ID、session存无效ID三个场景
  • current_role:当前账户存在、当前账户不存在两个场景

完整测试代码

require 'rails_helper'

RSpec.describe AdminController, type: :controller do
  # 测试数据可根据项目实际的FactoryBot配置调整
  let(:test_account) { Account.create!(name: '测试账户') }
  let(:test_user) { User.create!(name: '测试用户') }
  let(:test_role) { 'admin' } # 替换为项目实际的角色枚举值
  let!(:account_user) { AccountUser.create!(account: test_account, user: test_user, admin_role: test_role) }

  # 模拟鉴权框架的current_user返回值,使用Devise的场景可替换为sign_in方法
  before do
    allow(controller).to receive(:current_user).and_return(test_user)
  end

  describe '#current_account' do
    context 'session中存在有效current_account_id时' do
      before { session[:current_account_id] = test_account.id }
      it '返回对应的账户实例' do
        expect(controller.send(:current_account)).to eq test_account
      end
    end

    context 'session中不存在current_account_id时' do
      before { session[:current_account_id] = nil }
      it '返回nil' do
        expect(controller.send(:current_account)).to be_nil
      end
    end

    # 可选边界场景测试
    context 'session中存在无效current_account_id时' do
      before { session[:current_account_id] = 999999 }
      it '抛出ActiveRecord::RecordNotFound异常' do
        expect { controller.send(:current_account) }.to raise_error(ActiveRecord::RecordNotFound)
      end
    end
  end

  describe '#current_role' do
    context 'current_account存在时' do
      before { session[:current_account_id] = test_account.id }
      it '返回当前用户绑定的对应账户角色' do
        expect(controller.send(:current_role)).to eq test_role
      end
    end

    context 'current_account不存在时' do
      before { session[:current_account_id] = nil }
      it '返回默认用户角色' do
        expect(controller.send(:current_role)).to eq AccountUsers::DEFAULT_USER_ROLE
      end
    end
  end
end

适配说明

  • 测试中使用send调用私有方法,是RSpec控制器私有方法测试的通用写法
  • 如果不希望current_account在ID不存在时抛出异常,可以把原代码中的Account.find替换为Account.find_by(id: session[:current_account_id]),无匹配时直接返回nil

内容的提问来源于stack exchange,提问作者Muhammad Faseeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:06:01