7

I am writitng request spec for my rails app with capybara. In my code I have something like:

%table
  %tbody
     %tr{"on_click" => "location.href='some_link'"}
       %td="Some attribute"
       %td="Some attribute"
       %td="Some attribute"
       %td="Some attribute"

This way I make the entire row clickable. I want to write a request spec with capybara for this feature but I don't know how. Can anyone help me on this ?

Thank you

3 Answers 3

6

May be you should first get to know the testing in rails. Check this out! http://railscasts.com/episodes/275-how-i-test it is really helpful. You can give your tr a class (say) .tr and do

page.find(:css, ".tr").click()

I hope this works, worked in my case!

2
  • If I don't want to give it a class name, then what I am thinking is to do sth like: page.find('.table.tbody.tr', :text => "the entire row").click However I don't know how to write "the entire row" properly. From the code I wrote above, it can be "Some attribute Some attribute Some attribute Some attribute" but that doesn't work. Thanks anyway.
    – u19964
    May 25, 2012 at 18:34
  • I don't remember the exact syntax but may be you can do something like page.find(:xpath, ".//table/tbody/tr[1]").click()! May 25, 2012 at 18:42
5

I found this works without requiring a class:

page.find(:xpath, "//table/tbody/tr").click

I believe your row-click requires JavaScript, so you'll need to add :js => true to your test's header. Setting up testing with JavaScript is a challenge. I found these resources helpful:

Here is a more complete test example:

# Note that opening page by clicking on row requires JavaScript
describe "when user clicks on first row", :js => true do

  let(:first_account_listed) { Account.order(:name).first }

  before { page.find(:xpath, "//table/tbody/tr").click }

  it { should have_selector('title', text: 'Account Details') }

end
2

In Capybara 3+ you can go with a more elegant way by using the :table_row selector and match against a td value like:

page.find(:table_row, ["Some attribute"]).click

If you have table headers defined you can also pass a Hash instead of an Array that will match the cell against its corresponding table header like this:

page.find(:table_row, { "Header" => "Cell value" }).click

To dive into how this actually works, here's a link to the latest Capybara selector definition: https://github.com/teamcapybara/capybara/blob/master/lib/capybara/selector/definition/table_row.rb

1
  • 1
    Note that there is currently a bug which requires the curly braces when using the hash syntax. So this wouldn't work: page.find(:table_row, "Header" => "Cell value")
    – Andrew
    Nov 22, 2023 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.