Skip to content
Mike Miller edited this page Apr 3, 2019 · 1 revision

Helper methods are simply methods defined within the spec that help with testing. Methods can be defined within contexts and used by that context and all nested contexts.

Spectator.describe String do
  # This is a helper method.
  def random_string(length)
    chars = ('a'..'z').to_a
    String.build(length) do |builder|
      length.times { builder << chars.sample }
    end
  end

  describe "#size" do
    subject { random_string(10).size }

    it "is the length of the string" do
      is_expected.to eq(10)
    end
  end
end

Helper methods can access the same methods and values that an example can.

Spectator.describe String do
  # length is now pulled from value defined by `let`.
  def random_string
    chars = ('a'..'z').to_a
    String.build(length) do |builder|
      length.times { builder << chars.sample }
    end
  end

  describe "#size" do
    let(length) { 10 } # random_string uses this.
    subject { random_string.size }

    it "is the length of the string" do
      is_expected.to eq(length)
    end
  end
end

Additionally, helper methods can be defined in a separate module and included. In other words, helper methods can be used with mix-ins.

module StringHelpers
  def random_string
    chars = ('a'..'z').to_a
    String.build(length) do |builder|
      length.times { builder << chars.sample }
    end
  end
end

Spectator.describe String do
  include StringHelpers

  describe "#size" do
    let(length) { 10 }
    subject { random_string.size }

    it "is the length of the string" do
      is_expected.to eq(length)
    end
  end
end
Clone this wiki locally