Skip to content
Jelani Woods edited this page Jul 16, 2024 · 3 revisions

Welcome to the draft_matchers wiki!

Basic Usage

Color

expect(navbar).to have_background_color("blue")
expect(navbar).to have_color("white")
expect(navbar).to have_border_color("blue")

Position, Height, Width

expect(nav).to have_same_width_as(container)

expect(nav).to have_same_height_as(footer)

expect(nav).to be_next_to(div)

expect(label).to be_above(input)

expect(label).to be_directly_above(input)

Next to other element

top_el = el.rect.top
bottom_el = el.rect.bottom 
        
other_top = other_el.rect.top 
        expect(top_el..bottom_el).to cover(other_top)

Probably want to round, b/c this is annoying

Expected the top of 'menu.jpg' to be between 1600.015625 and 1659.015625, but was 1600 instead.

Label matches Input

 
    address_label = find("label", :text => /Zip Code/i)
    for_attribute = address_label[:for]

    if for_attribute.empty?
      expect(for_attribute).to_not be_empty,
        "Expected label’s for attribute to be set to a non empty value, was '#{for_attribute}' instead."
    else
      all_inputs = all("input")
  
      all_input_ids = all_inputs.map { |input| input[:id] }
  
      expect(all_input_ids.count(for_attribute)).to eq(1),
        "Expected label’s for attribute(#{for_attribute}) to match only 1 of the ids of an <input> tag (#{all_input_ids}), but found 0 or more than 1."
    end

Replacement for fill_in

  • now allows case insensitivity for label text
  • more descriptive error message if label doesn't have matching input
    number_label = find("label", :text => /Enter a number/i)
    for_attribute = number_label[:for]
    begin
      number_input = find("##{for_attribute}")
    rescue Capybara::ElementNotFound
      expect(false). to be(true), "Expected to find an <input> with an id attribute that matched the for attribute of a <label> (#{for_attribute}) but didn't find one."
    end
    number_input.set(5)

Get Parent Element

element.find(:xpath, "..") vs element.parent

Assert child element

expect(page).to have_css("nav a", :text => /Sign In/i),
      "Expected page to have an a tag with text ‘Sign In' inside a nav, but didn’t find one."

Better

expect("nav").to have_child("a")

# implementation
# el.tag_name + child_arg
# = have_css("tag child", opts)

Find by aria label

https://stackoverflow.com/questions/71769787/finding-a-button-in-capybara

find('button[aria-label="Open Cow menu"]').click