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
相关产品推荐
相关产品推荐

