如何在RSpec文件中重构辅助方法?

时间:2011-09-30 19:40:22

标签: ruby-on-rails ruby ruby-on-rails-3 refactoring rspec

我正在使用Ruby on Rails 3.1.0和rspec-rails 2 gem。我想重构下面的代码(我故意省略了一些代码,并且我给出了有意义的名称以突出显示结构):

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相关方法(包含RoR session),运行spec文件时出现以下错误:

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

1 个答案:

答案 0 :(得分: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