Ruby 如何确定RSpec将运行哪些示例

Ruby 如何确定RSpec将运行哪些示例,ruby,rspec,Ruby,Rspec,我想在运行任意RSpec测试之前执行一些代码,但仅在要测试的示例组位于特定目录或带有特定标记的情况下 例如,如果我有以下组: ## spec/file_one.rb describe "Spec One - A group which needs the external app running", :external => true do describe "Spec Two - A group which does not need the external app running"

我想在运行任意RSpec测试之前执行一些代码,但仅在要测试的示例组位于特定目录或带有特定标记的情况下

例如,如果我有以下组:

## spec/file_one.rb
describe "Spec One - A group which needs the external app running", :external => true do

describe "Spec Two - A group which does not need the external app running" do

## spec/file_two.rb
describe "Spec Three - A group which does NOT need the external app running" do

## spec/always_run/file_three.rb
describe "Spec Four - A group which does need the external app running"
然后,我希望代码仅在测试运行包含Spec 1或Spec 4时执行


当我可以依赖文件名时,这相对容易做到,但当依赖标记时,这就更难做到了。如何检查示例将运行哪些文件,然后检查它们的标记?

我只需要这样的支持设置:

PID_FILE = File.join(Rails.root, "tmp", "pids", "external.pid")

def read_pid
  return nil unless File.exists? PID_FILE
  File.open(PID_FILE).read.strip
end

def write_pid(pid)
  File.open(PID_FILE, "w") {|f| f.print pid }
end

def external_running?
  # Some test to see if the external app is running here
  begin
    !!Process.getpgid(read_pid)
  rescue
    false
  end
end

def start_external
  unless external_running?
    write_pid spawn("./run_server")        
    # Maybe some wait loop here for the external service to boot up
  end
end

def stop_external
  Process.kill read_pid if external_running?
end

RSpec.configure do |c|
  before(:each) do |example|
    start_external if example.metadata[:external]
  end

  after(:suite) do
    stop_external
  end
end
每个标有
:external
的测试都会尝试启动尚未启动的外部进程。因此,当您第一次运行需要它的测试时,该进程将被引导。如果没有运行带有标记的测试,则永远不会启动进程。然后,套件通过作为关闭过程的一部分终止该过程来进行自我清理

这样,您就不必预先处理测试列表,您的测试也不相互依赖,并且您的外部应用程序在测试后会自动清理。如果外部应用程序在测试套件有机会调用它之前运行,它将读取pid文件并使用现有实例


您可以解析示例的全名,并确定是否需要外部应用程序进行更“神奇”的设置,而不是依赖
元数据[:external]
,但这对我来说有点难闻;示例描述是针对人类的,不是针对要解析的规范套件。

代码不是专门针对外部的,但答案同样相关,谢谢!