Is it possible to test the order of elements via RSpec/Capybara?

I found a more canonical way of testing this behaviour with CSS. You could user :first-child, :last-child and :nth-child(n) selectors in whichever assert you like.

In your example I'd try these assertions:

page.should have_tag("ul:last-child", :text => "ITEM #1")
pseuo_add_new_li
page.should have_tag("ul:nth-last-child(2)", :text => "ITEM #1")
page.should have_tag("ul:last-child", :text => "ITEM #2")

I hope this helps someone. Read more about this.


I resolved this issue by testing for a regex match against the body content of the page. A bit kludgy, but it works.

page.body.should =~ /ITEM1.*ITEM2.*ITEM3/

this article lists several ways to test sort order in RSpec, the best of which seems to be this matcher:

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