2011-09-30 67 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