Ruby RSpec 仅为一个上下文定义 before/after 挂钩

Ruby RSpec define before/after hooks for one context only

我有以下 RSpec 测试结构:

RSpec.describe A do
  context C1 do
    it EX1a do
    end
    ....
    it EX1n do
    end
  end
  context C2 do
    it EX2a do
    end
    ...
  end
end

我现在要定义一个挂钩,它只为上下文 C1 中的示例运行设置和关闭 wordk。我怎样才能做到这一点?按照我的理解of the structuring of the hooks,使用before(:context)会在每个上下文(包括C2)之前执行一次,而before(:example)会在每个示例(包括EX2a)之前执行一次,这不是我的意思想要。

我有 RSpec 3.8

不完全是。这取决于您放置 before 块的位置。当你把它们放在这样的上下文中时

RSpec.describe A do
  context C1 do
    before { do_something }

    it EX1a do
    end
    it EX1n do
    end
  end
  context C2 do
    it EX2a do
    end
  end
end

那么before回调只会在运行宁EX1aEX1n之前执行,而不会在EX2a.

之前执行

before(:context) 块类似。引用文档:"before(:context) 运行 仅一次,在一组中的所有示例之前"=27=]。一个 context 块定义了一个 group.