List all cucumber step definitions

There’s a lot of implementations out there for how to list the cucumber step definitions in an application.  This is my version, which outputs a sorted list to your browser.  Special thanks to Nat on Testing to get me started with his code.)

I put this code into the file “helpers/step_definition_helper.rb”.


In the Rails Console:

include StepDefinitionHelper

The Code:

# Methods in this helper create a list of existing step definitions which is useful to the developer of features.
module StepDefinitionHelper
  # Outputs all the step definitions to an HTML file, sorted by regex.
  # To use:
  # From the Rails Console:
  # include StepDefinitionHelper
  # step_definitions_to_html
  def step_definitions_to_html
    # Where are your step definitions defined?
    step_definition_dir = "./features/step_definitions"
    # Where do you want output to go:
    outfile = "output.htm"
    steps = get_step_definitions(step_definition_dir)   # get the step definitions
    steps = steps.sort_by {|step| step.regex}           # sort them
    output_step_definitions_as_html(outfile, steps)     # output as HTML
    show_html(outfile) # show the file in the browser

  def get_step_definitions(step_definition_dir)
    steps = []
    Dir.glob(File.join(step_definition_dir,'**/*.rb')).each do |step_file| do |line|
        next unless line =~ /^\s*(?:Given|When|Then)\s+\//
        matches = /(?:Given|When|Then)\s*\/(.*)\/([imxo]*)\s*do\s*(?:$|\|(.*)\|)/.match(line).captures
        matches << step_file
        steps << matches[0], modifiers: matches[1], args: matches[2], source_file: matches[3])

  def output_step_definitions_as_html(fn, steps)
    f =, "w")
    f << "<table><th>Regex</th><th>Modifiers</th><th>Step Definition Args</th><th>Source file</th>"
    steps.each do |step|
      f << "<tr>"
      f << "<td>#{step.regex}</td>"
      f << "<td>#{step.modifiers}</td>"
      f << "<td>#{step.args}</td>"
      f << "<td>#{step.source_file}</td>"
      f << "</tr>"
    f << "</table>"

  def show_html(outfile)
    require "launchy"
    full_path = 'file:///' + File.join(Rails.root.to_s, outfile)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s