Backo
Backo

Reputation: 18871

How to refactor helper methods in RSpec files?

I am using Ruby on Rails 3.1.0 and the rspec-rails 2gem. I would like to refactor the following code (I have intentionally omitted some code and I have given meaningful names in order to highlight the structure):

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

What can\should I make in order to refactor the above code?

P.S.: I have tried to extract helper methods in an external module (named Sample) but, for example relating to the D1_C1_Method_1 method (that contains the RoR session), I get the following error when I run the spec file:

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

Upvotes: 3

Views: 2823

Answers (1)

tokland
tokland

Reputation: 67870

Have you tried to include the helpers as an external module?

require 'path/to/my_spec_helper'

describe "D1" do
  include MySpecHelper
  ...
end

And now the helper:

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

Upvotes: 3

Related Questions