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

RSpec自定义匹配器中如何获取当前上下文?

在RSpec自定义匹配器中获取当前上下文

可以通过RSpec.current_example访问当前测试实例,进而提取你需要的上下文信息。

修改后的匹配器代码示例:

RSpec::Matchers.define :be_the_same do |expected|
  match do |actual|
    # 获取当前测试实例
    current_example = RSpec.current_example
    # 提取当前context的描述文本
    context_desc = current_example.example_group.description
    # 这里就能拿到你要的'some context'
    puts context_desc

    actual == expected
  end
end

RSpec.describe do 
  context 'some context' do 
    it { expect(1).to be_the_same(1) }
  end
end
  • RSpec.current_example会返回当前正在执行的测试实例对象
  • 通过example_group.description可以直接获取当前context或describe块的描述内容
  • 如果需要获取更上层的上下文,可通过example_group.parent遍历父级分组来提取对应信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:03:37