views:

325

answers:

2

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>
A: 

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"
JosephL
Changing application code for tests to work is a big NONO
artemave
What I was actually expecting is for someone to show how to use Nokogiri in Webrat, since the former brings xpath selectors.
artemave
A: 

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/)

Balint Erdi