定义任意辅助方法

您可以使用 Ruby 的 def 关键字或 define_method 方法在任何示例组中定义方法。这些辅助方法将公开给定义它们的组中的示例以及嵌套在该组中的组,但不公开给父级或同级组。

使用在同一组中定义的方法

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.describe "an example" do
  def help
    :available
  end

  it "has access to methods defined in its group" do
    expect(help).to be(:available)
  end
end

我运行 rspec example_spec.rb

那么示例应该全部通过。

使用在父组中定义的方法

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.describe "an example" do
  def help
    :available
  end

  describe "in a nested group" do
    it "has access to methods defined in its parent group" do
      expect(help).to be(:available)
    end
  end
end

我运行 rspec example_spec.rb

那么示例应该全部通过。