2011-09-30 38 views
3

我正在使用Ruby on Rails 3.1.0和rspec-rails 2 gem。我想重構下面的代碼(我故意省略了一些代碼,我已經爲了突出結構給出有意義的名稱):如何重構RSpec文件中的輔助方法?

describe "D1" do 
    # Helper method 
    def D1_Method_1 
    ... 
    end 

    context "C1" do 
    # Helper methods 
    def D1_C1_Method_1 
     session.should be_nil # Note: I am using the RoR 'session' hash 
     D1_Method_1   # Note: I am calling the 'D1_Method_1' helper method 
     ... 
    end 

    def D1_C1_Method_2 
     ... 
    end 


    it "I1" do 
     D1_Method_1 
     ... 
    end 

    it "I2" do 
     ... 
     D1_C1_Method_1 
     D1_C1_Method_2 
    end 
    end 

    context "C2" do 
    # Helper methods 
    def D1_C2_Method_1 
     ... 
    end 

    def D1_C2_Method_2 
     ... 
    end 


    it "I1" do 
     D1_Method_1 
     ... 
    end 

    it "I2" do 
     ... 
     D1_C2_Method_1 
     D1_C2_Method_2 
    end 
    end 
end 

我應該以重構上面的代碼有什麼可以\ ?

PS:我試圖提取外部模塊(名爲Sample)在輔助方法但是,例如涉及到D1_C1_Method_1方法(包含回報率session),我收到以下錯誤,當我運行spec文件:

Failure/Error: session.should be_nil 
NameError: 
    undefined local variable or method `session' for Sample:Module 
+1

我有同樣的問題;這幫了我: https://www.relishapp.com/rspec/rspec-core/docs/helper-methods/define-helper-methods-in-a-module – yepUknow

回答

2

您是否嘗試過將助手作爲外部模塊?

require 'path/to/my_spec_helper' 

describe "D1" do 
    include MySpecHelper 
    ... 
end 

而現在的幫手:

# my_spec_helper.rb 
module MySpecHelper 
    def D1_C1_Method_1 
    session.should be_nil 
    ... 
    end 
end 
+0

我有一個'spec/support'目錄。 ..我應該如何陳述(絕對或相對)路徑? – Backo

+0

需要'support/my_helper' – tokland