2013-04-11 53 views
0

我想在运行任意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" 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" 

那我要当一个测试运行包含规格的一个或规格四要执行代码。

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

回答

2

我只希望有一个支持的设置是这样的:

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文件并使用现有的实例。

而不是依靠metadata[:external]您可以解析示例的全名,并确定是否需要外部应用程序更“神奇”的设置,但这对我来说有点臭;示例描述适用于人类,不适用于spec套件解析。

+0

该代码不是特定的外部,但答案是一样相关,谢谢! – 2013-05-15 20:51:29

相关问题