WEB Last Wolf
WEB Last Wolf

Reputation: 122

Is it possible to find out if an element comes before the second element in Capybara?

I was doing tests with Caplybara, Cucumber and WebDriver, so I looked at two elements on top of each other, so I thought.

The structure is simple

<div id="father-parent">
    <p id="children-0">Firt element</p>
    <p id="children-1">Second element</p>
</div>

Upvotes: 1

Views: 960

Answers (3)

Matt
Matt

Reputation: 5398

If you can do with simple content matching, I have just added a new matcher as spec/support/matchers/appear_before_matcher.rb:

RSpec::Matchers.define :appear_before do |later_content|
  match do |earlier_content|
    page.body.index(earlier_content) < page.body.index(later_content)
  end
end

and then used it like this:

expect('First element').to appear_before('Second element')

Upvotes: 3

Maximo Mussini
Maximo Mussini

Reputation: 1361

Depending on how the test is written, you could also use the have_sibling matcher:

first_child = find('#children-0')
expect(first_child).to have_sibling('#children-1')

To test for element positions, some drivers support the :below filter:

expect(first_child).to have_sibling('#children-1', below: first_child)

below is one of Capybara's global filters, you could also use above, left_of, and right_of.

Upvotes: 1

Thomas Walpole
Thomas Walpole

Reputation: 49890

If what you're trying to verify is that children-0 comes right before children-1 you can use the CSS adjacent sibling selector

expect(page).to have_css('#children-0 + #children-1')

If you just want to verify that children-0 is a prior sibling of children-1 (not necessarily adjacent) you can use the general sibling selector

expect(page).to have_css('#children-0 ~ #children-1')

Upvotes: 1

Related Questions