Search code examples
ruby-on-railsruby-on-rails-4capybararspec-rails

Rails 4 Capybara how to test the exact order of the input fields in a form


In my Rails 4 app, I have a form for the user to set a new password. I want to test this with Capybara and test the order of the input fields as I need to be sure they are always in a certain order in the UI.

in my UI I have:

input[@id = "user_current_password"]
input[@id = "user_password"]
input[@id = "user_password_confirmation"]

My test, for now, looks like:

it 'changing the expired password' do

    render

    expect(rendered).to have_content("Update Password")
    expect(rendered).to have_content("Current Password:")
    expect(rendered).to have_content("New Password:")
    expect(rendered).to have_content("Confirm New Password:")
    expect_submit_button("Change Password")

    # Boxes order
    current_password = page.has_xpath?('//input[@id = "user_current_password"]')
    new_password = page.has_xpath?('//input[@id = "user_password"]')
    confirm_new_password = page.has_xpath?('//input[@id = "user_password_confirmation"]')

  end

I need to add a way to check the input fields are always in the same order. So if for some reason the order change I see the test fail.


Solution

  • rendered in view specs is just a string containing the HTML so depending on exactly what the HTML looks like the simplest method would just be a regexp

    rendered.match?(/id="user_current_password".+id="user_password".+id="user_password_confirmation"/m)
    

    If you wanted to get more "correct" and actually verify structure you could potentially use has_xpath? using the following-sibling axis or possibly has_css? with an adjacent sibling selector (+), but to provide those queries we'd need to see the actual HTML.