Flo Rahl
Flo Rahl

Reputation: 1054

Capybara Ambiguous match - how to select first item

I have a page with multiple buttons. For example :

<% Zombie.each.do |zombie| %>
  <%= zombie.name %>
  <%= form_for(zombie) do |f| %>
    <div><%= f.hidden_field :craving, value: true %></div>
    <%= f.submit t('zombie.craving') %>
  <% end %>
<% end %>

And I want to test

it "should increment the craving zombie count" do
  expect { click_button t('zombie.craving') }.to change(Zombie.where(craving: true), :count).by(1)
end

But if I do that, Capybara detect as much ambiguous match as there are Zombies...

How can I do to circumvent this ?

Upvotes: 3

Views: 1456

Answers (1)

jokklan
jokklan

Reputation: 3540

You should add a class or id to your form that is different for each zombie (like "zombie_#{id}"). Rails has a helper method that does this for you

<%= form_for(zombie, :html => { :id => dom_id(zombie) }) do |f| %>

Then in your tests can you add a within:

it "should increment the craving zombie count" do
  zombie = Zombie.where(craving: true).first

  within "#zombie_#{zombie.id}" do
    expect { click_button t('zombie.craving') }.to change(zombie, :count).by(1)
  end
end

Upvotes: 2

Related Questions