An auto-mapper for BEM classes in Cucumber selectors

Updated . Posted . Visible to the public.

When you are using the #selector_for helper in Cucumber steps, as e.g. Spreewald Show archive.org snapshot does, the following snippet will save you typing. It recognizes a prose BEM-style selector and maps it to the corresponding BEM class.

For a variation on this idea, see An auto-mapper for ARIA labels and BEM classes in Cucumber selectors.

Examples

"the main menu" -> '.main-menu'
"the item box's header" -> '.item-box--header'

Here are some examples of steps (using Spreewald, too):

Then I should see "Bruce Wayne" within the header's user name
# matches .header--user-name

When I click on the gallery image that is featured
# clicks on .gallery-image.is-featured

Code

Save this to features/support/selectors.rb, or update your file:

module HtmlSelectorsHelpers
  def selector_for(locator)
    case locator

    # Auto-mapper for BEM classes
    #
    # Usage examples:
    #   the main menu -> '.main-menu'
    #   the item box's header -> '.item-box--header'
    #   the slider's item that is current -> '.slider--item.is-current'
    when /^the (.+?)(?:'s (.+?)(?: that (.+))?)?$/
      selector = '.'
      selector << selectorify($1)
      selector << '--' << selectorify($2) if $2
      selector << '.' << selectorify($3) if $3
      selector
    
    else
      raise "Can't find mapping from \"#{locator}\" to a selector.\n" +
        "Now, go and add a mapping in #{__FILE__}"
    end
  end
  
  private

  def selectorify(string)
    string.gsub(/ /, '-')
  end

end

World(HtmlSelectorsHelpers)
Dominik Schöler
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2015-02-20 16:51)