Perry Horwich
Perry Horwich

Reputation: 2846

Testing order of lines of text on web page - Rspec & Capybara in rails

Maybe I am missing the obvious...

I can easily test for the presence or absence of text on a web page.

Is there a straightforward way to test for the order of items listed in a div or on a web page, say from top to bottom?

So, if I am expecting

  1. This
  2. That
  3. The other thing
  4. And one more item

... to be displayed in that order. Is there a matcher or test method that can be invoked to check the web page content? It should fail if something like this were displayed:

  1. This
  2. The other thing
  3. That
  4. And one more item

Upvotes: 5

Views: 2817

Answers (4)

Rimian
Rimian

Reputation: 38418

You could do it with CSS or XPath selectors:

expect(page.find('li:nth-child(1)')).to have_content 'This'

http://www.w3schools.com/cssref/sel_nth-child.asp

Also see:
http://makandracards.com/makandra/9465-do-not-use-find-on-capybara-nodes-from-an-array

Upvotes: 6

Ryan Ashton
Ryan Ashton

Reputation: 31

You could do something like this using RSpec Matchers/Index

  def items_in_order
    page.body.index('This').should < page.body.index('That') &&
        page.body.index('That').should < page.body.index('The other thing') && 
            page.body.index('The other thing').should < page.body.index('And one more item')
  end

Upvotes: 3

Andrei Botalov
Andrei Botalov

Reputation: 21096

As a variant:

 expect(some_el).to have_text(/This .+ That .+ The other thing .+ And one more item/)

Upvotes: 0

Markus
Markus

Reputation: 5807

If the order of display is the same as in the html, for example:

<div id="one">This</div>
<div id="two">That</div>
<div id="three">The other thing</div>
<div id="four">And one more item</div>

Then it should be possible like this:

it "should have the right order" do
    elements = all('#one, #two, #three, #four'); # all in one selector
    expect(elements[0]['id']).to eql('one');
    expect(elements[1]['id']).to eql('two');
    expect(elements[2]['id']).to eql('three');
    expect(elements[3]['id']).to eql('four');
end

The order of elements should be the same like they appear in the document. Tested it by myself.

Upvotes: 1

Related Questions