Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 508
Perry Horwich Avatar asked Dec 25 '14 22:12

Perry Horwich


3 Answers

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

like image 171
Rimian Avatar answered Nov 14 '22 21:11

Rimian


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
like image 24
Ryan Ashton Avatar answered Nov 14 '22 23:11

Ryan Ashton


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.

like image 27
Markus Avatar answered Nov 14 '22 21:11

Markus