Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing focus with Capybara

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.

like image 229
Jakub Arnold Avatar asked Oct 29 '11 17:10

Jakub Arnold


People also ask

What is Capybara testing?

Capybara is a web-based test automation software that simulates scenarios for user stories and automates web application testing for behavior-driven software development. It is written in the Ruby programming language. Capybara.


3 Answers

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? :)

like image 121
cutalion Avatar answered Sep 22 '22 16:09

cutalion


You should use the :focus selector, e.g:

page.should have_selector('#category_name:focus')
like image 32
Mike Aski Avatar answered Sep 24 '22 16:09

Mike Aski


With the Selenium driver you can get the focused element:

page.driver.browser.switch_to.active_element

Then you can do what you like with it

page.driver.browser.switch_to.active_element.send_keys "some text"

Note that it returns a Selenium::WebDriver::Element whereas find returns a Capybara::Node::Element so be careful when comparing them

expect(page.driver.browser.switch_to.active_element).to eql(find('#some-element').native)
like image 22
Tamlyn Avatar answered Sep 22 '22 16:09

Tamlyn