Ruby 1.9.3, Rails 3.1.10, RSpec 2.13.0, Capybara 2.2.1
I am on a page in the app that uses nested forms. The form adds members to a queue. If a member is already saved, the id of that member (in the HTML) is queue_queue_members_attributes_0_user_id
, followed by 1, 2 and so on. When I click the link to Add New Member
via JavaScript, the HTML id of the new select box is something like: queue_queue_members_attributes_1421760178806_user_id
As you can see, a random string of numbers is generated for every new select box, in which the nested-attribute has yet to be saved. I need to know the id of this HTML element in order to effectively test with Capybara.
I am on a page that adds members to a queue. If members are already present, the ids of their select boxes are 0, 1, so on. If I click "Add New Member", the id of the new select box is a randomly generated number, in this case 1421760178806.
Original Attempt
Below is a helper method I made for the spec. It worked initially. Recently, however, I needed to test for queue members. When I added a queue member factory, and created one with a new queue factory instance, this problem began. Because now I have 2 select boxes matching the xpath query
def select_member(member)
find(:xpath, "//select[contains(@id, '_user_id')]/option[@value='#{member.id}']").select_option
end
Failure/Error: select_member(@test_user)
Capybara::Ambiguous:
Ambiguous match, found 2 elements matching xpath "//select[contains(@id, '_user_id')]/option[@value='6647']"
With my changes, a member is added to a queue upon creation via FactoryGirl. This means my xpath expression matches both select boxes -- one with id 0 and the other 1421760178806. I only want it to match the latter number (anything but a single "0".) My tests only add a single member, so I am not worrying about ids >0.
Second Attempt
I found this SO question initially helpful, until I ran into another error.
def select_member(member)
find(:xpath, "//select[matches(@id, '[0-9]{2,}_user_id')]/option[@value='#{member.id}']").select_option
end
Failure/Error: select_member(@test_user)
Capybara::Webkit::InvalidResponseError:
INVALID_EXPRESSION_ERR: DOM XPath Exception 51