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

循环内RSpec describe/context标签引用外部变量异常求助

RSpec循环遍历外部变量定义context时崩溃问题

无法判断是操作错误还是Bug,我已提交Bug报告。我需要在循环中使用describe/context块,但访问RSpec.describe块外部变量时出现异常。

这是一个多用户角色的应用,我计划用中心变量存储所有角色(如[:staff, :company_lead, ...]),在请求测试中遍历使用。

使用版本信息:

  • rspec-core(3.12.2/3.12.1)
  • rspec-rails(6.1.0/6.0.1)
  • Rails 6.1
  • Ruby 2.7.2

在新版本项目(Ruby 3.2.2、Rails 7.0.5、rspec-rails 6.0.1)测试时仍有相同问题,但早年的GitHub示例曾正常运行。

正常运行的代码

RSpec.describe '/admin/settings', type: :request do
  ALLOWED_ROLES = %i[adm bo_adm]
  ALLOWED_ROLES.each do |role|
    describe "allowed as #{role}" do
      login("user_#{role}")
      it "check" do
        expect(1).to eq(2)
      end
    end
  end
end

测试按预期失败。

可运行但有缺陷的代码

class Tests
  SUBTESTS = [:adm, :bo_adm]
end
RSpec.describe '/admin/settings', type: :request do
  Tests::SUBTESTS.each do |v|
    context "as_role_" do
      it "check" do
        expect(1).to eq(2)
      end
    end
  end
end

测试可运行并失败,但无法区分子测试,因为context标签是固定的。

运行崩溃的代码

class Tests
  SUBTESTS = [:adm, :bo_adm]
end
RSpec.describe '/admin/settings', type: :request do
  Tests::SUBTESTS.each do |v|
    context "as_role_#{v}" do
      it "check" do
        expect(1).to eq(2)
      end
    end
  end
end

当context标签引入变量v时,测试崩溃,提示“未找到测试...所有示例已被过滤”。

除了将数组Tests::SUBTESTS放在RSpec.describe块外部,我和第一个测试没有其他差异。我是否遗漏了什么?有没有其他实现方式?目前我在/spec/support/controller_macros.rb中定义了login_as...方法,希望在其中存放角色数组,供/spec/requests/...下的测试访问,但始终无法实现。

感谢您的帮助。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:33:28