Read more

An auto-mapper for BEM classes in Cucumber selectors

Dominik Schöler
February 20, 2015Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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)
Posted by Dominik Schöler to makandra dev (2015-02-20 17:51)