selecting page elements with webrat

筅森魡賤 提交于 2020-01-07 04:34:12

问题


There is a list of products (html table). Each row has got product name and ends with 'add to cart' button. How to add 2 'coffee' and 3 'tea' in the cart from webrat?

Corresponding html:

<tr class="odd">
      <td><img src="/images/menu_items_images/7/PICT0020_thumb.jpg" /></td>
      <td>cofee</td>
      <td>americano</td>
      <td>1.0</td>
      <td><form action="/cart/add_item/7" method="post" onsubmit="$.ajax({data:$.param($(this).serializeArray()) + '&amp;authenticity_token=' + encodeURIComponent('rDzsxOQSgwTT3rjUDROFGNz4hMs6BK0riGemVi+NHK4='), dataType:'script', type:'post', url:'/cart/add_item/7'}); return false;"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="rDzsxOQSgwTT3rjUDROFGNz4hMs6BK0riGemVi+NHK4=" /></div>            <input name="commit" type="submit" value="Add to cart" /></form></td>
</tr>
<tr class="even">
      <td><img src="/images/menu_items_images/6/PICT0053_thumb.JPG" /></td>
      <td>tea</td>
      <td>green</td>
      <td>2.0</td>
      <td><form action="/cart/add_item/6" method="post" onsubmit="$.ajax({data:$.param($(this).serializeArray()) + '&amp;authenticity_token=' + encodeURIComponent('rDzsxOQSgwTT3rjUDROFGNz4hMs6BK0riGemVi+NHK4='), dataType:'script', type:'post', url:'/cart/add_item/6'}); return false;"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="rDzsxOQSgwTT3rjUDROFGNz4hMs6BK0riGemVi+NHK4=" /></div>            <input name="commit" type="submit" value="Add to cart" /></form></td>
</tr>

回答1:


Give your Add to cart buttons ids like id="add_item_6" then you can use webrat to click the button you want.

When /^I press Add to cart for "([^\"]*)"$/ do |item|
  id = Item.find_by_name(item).id
  click_button('add_item_' + id.to_s)
end

Then your step would be

When I press Add to cart for "coffee"



回答2:


I would argue that adding the id to the link is in fact semantic markup, a good practice. If you don't want to use it, though, I think you can use the position() predicate (see http://www.w3.org/TR/xpath/)



来源:https://stackoverflow.com/questions/1476604/selecting-page-elements-with-webrat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!