2014-02-13 109 views
1

我想使用around hook來使用臨時目錄運行我的規範,並在之後清理臨時目錄。如何從上下文中將上下文傳遞給示例

describe FileManipulatingClass do 

    around(:each) do |example| 
    Dir.mktmpdir do |dir| 
     example.run 
    end 
    end 

    subject { described_class.new dir } 

    context "given its help file exists" do 
    let(:file_path) { File.join dir "help.txt"} 
    before(:each) do 
     File.open(file_path, 'w') {|io| io.write "some data" } 
    end 

    its(:help_text) { should eq("some data") } 

    end 

end 

這不起作用,因爲沒有爲上下文設置「目錄」。我該怎麼做相當於

let(:dir) { ... } 

並提供一個值,只有在掛鉤可用?

回答

3

一種方法是你around鉤內設置一個實例變量,如下所示:

describe FileManipulatingClass do 

    around(:each) do |example| 
    Dir.mktmpdir do |dir| 
     @dir = dir 
     example.run 
    end 
    end 

    subject { described_class.new @dir } 

    context "given its help file exists" do 
    let(:file_path) { File.join @dir "help.txt"} 
    before(:each) do 
     File.open(file_path, 'w') {|io| io.write "some data" } 
    end 

    its(:help_text) { should eq("some data") } 

    end 

end 
+0

謝謝,彼得。如果你在與周圍區塊相同的範圍內包含一個let,那麼這很有效。對我的目的來說這很好。所以上述不起作用,但您可以通過在主題行之前添加另一個let(:dir){@dir}來輕鬆糾正它的工作方式。 – Ritchie

+0

我同意你可以在你的建議編輯中使用'let'(它會是更好的樣式),但我相信上面的例子是按原樣運行的。你有沒有注意到我在傳遞給'subject和'let'的塊中將'dir'改成了'@ dir'? –

+0

我終於開始測試這個。你是對的。您可以直接在其他作用域中使用實例變量。 – Ritchie

相關問題