Alex Rivera | Logout

Testing focus with Capybara

Asked 2011-10-29T17:34:18.633
18

I have a simple link_to_function in my view template

<%= link_to_function "add new category", "$('#category_name').focus()" %>

and I want to test this with capybara using request specs. Basically the spec should look something like this

it "focuses category form when I click 'add new category'" do
  visit new_article_path
  click_link "add new category"

  # unfortunately there's nothing like 'has_focus?'
  find_field("category_name").should have_focus  
end

the problem is, I wasn't able to find anything, that would check if the element has focus. The only thing I did find was this

page.evaluate_script('document.focus')[:id]

which however isn't supported by the capybara-wekbit driver, which I'm using to avoid opening browser for each test run.

Edit
Report

1 Answer

32

I just used the following code (with phantomjs driver, but I believe that it works with webkit also):

page.evaluate_script("document.activeElement.id") == "some_id"

P.S. One year question without an answer. Should they give me a badge? :)

answered 2012-11-01T12:54:20.373

Your Answer