2011-08-02 46 views
0

我想在每個鉤子之前創建一個tmpdir,並在rspec示例中使用它的路徑。我想要使​​用Dir.mktmpdir的塊形式,以便在示例結束時刪除目錄。如何在帶rspec的鉤子中使用Dir.mktmpdir塊?

問題:

  • 我不能讓在該塊退出掛鉤之前,或在我的例子可以運行目錄被刪除。
  • 我無法圍繞我的示例換行。我嘗試使用大約 掛鉤,但不會與示例共享實例變量( doc確認此行爲)。

目前,我正在使用continuations(纖維會更好,如果我在1.9上)跳出該塊,然後跳回來,以便mktmpdir可以清理。

有沒有更簡單的方法來實現這一點,而不必在每個示例中移動mktmpdir?確實,我可以在後臺刪除目錄,但我也在尋找這種類型的問題的一般解決方案 - 我並不總是知道當塊退出時清理代碼應該運行什麼。

僅供參考,我繼續碼,封裝成一個類:

class SuspendableBlock 
    def initialize 
    end 

    def run(&block) 
    raise LocalJumpError unless block_given? 
    callcc {|@run_cc| 
     yield 
     @resume_cc.call if @resume_cc 
    } 
    nil 
    end 

    # saves the suspend point & causes run to return immediately 
    def suspend 
    raise "run must be called first" unless @run_cc 
    callcc {|@suspend_cc| 
     @run_cc.call(@suspend_cc) 
    } 
    nil 
    end 

    # jumps back to after the suspend point to finish the block. 
    # after the block exits, return immediately from resume. 
    def resume 
    raise "suspend must be called first" unless @suspend_cc 
    callcc {|@resume_cc| 
     @suspend_cc.call(@resume_cc) 
    } 
    nil 
    end 
end 

用法:

before :each do 
    @sb = SuspendableBlock.new 
    @sb.run do 
    Dir.mktmpdir do |dir| 
     @tmpdir_path = Pathname.new(dir) 
     @sb.suspend 
    end 
    end 
end 

after :each do 
    @sb.resume 
end 

it "should use a tmp dir" do 
    p @tmpdir_path 
end 

回答

1

從我讀(從來沒有測試)的延續真的是低效的。

雖然我不能幫你繼續,你可以使用Thread來模仿Fibers:https://github.com/tmm1/fiber18

已經有一個庫是em-spec(https://github.com/tmm1/em-spec),每個測試都在光纖中運行,您可以根據需要對其進行修改。

相關問題