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.
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.
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? :)
You should use the :focus
selector, e.g:
page.should have_selector('#category_name:focus')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With