Watir: selector for an a-href inside the first table cell

863 Views Asked by At

I have my css alias like:

module MyPage

  def locator(key, *options)
    hash = {
        "FIRST_TABLE_CELL_HREF" => [ :css => '#my-table td:nth-child(1):first a']
    }
  end

I want to click on that alias:

@page.find("FIRST_TABLE_CELL_HREF").when_present.right_click

Problem: that's a Javascript style alias, so it doesn't work.

Question: how to write the same Ruby style css alias?

P.S. $('#my-table td:nth-child(1):first a') works well in browser console.

For @TitusFortner that's true when you want to select specific element. But I'm using some business level language (Gherkin in my case) and I want to write an universal instruction. It'd look like When I right click on the element "FIRST_TABLE_CELL_HREF". That instruction would be mapped to:

When(/^I right click(?: on|)(?: the|) "([^\"]*)"$/i) do |scope|
  @page.find(scope).when_present.right_click
end

Where @page = @browser.visit(SomePage), where in turn @browser = BrowserBase.new start_browser(ENV['BROWSER'])

1

There are 1 best solutions below

1
On BEST ANSWER

With Watir you often don't even need to use css

browser = Watir::Browser.new

First link in the table:

browser.table(id: 'my-table').link

Link in first data cell in table:

browser.table(id: 'my-table').td.link

If it has to be just css for some reason:

browser.link(css: '#my-table a')

Also if your table is within the context of an iframe, you have to explicitly declare it, because the driver can only see the top level browsing context unless specifically switched to. With Watir this would work:

browser.iframe(id: 'iframe_id').table(id: 'my-table').link

This would not work:

browser.link(css: '#iframe_id #my-table a')