用水豚测试焦点
我的视图模板中有一个简单的 link_to_function
<%= link_to_function "add new category", "$('#category_name').focus()" %>
,我想使用请求规范使用水豚来测试它。基本上规范应该看起来像这样
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
,问题是,我找不到任何可以检查元素是否具有焦点的东西。 我发现的唯一一件事是它
page.evaluate_script('document.focus')[:id]
不受 capybara-wekbit 驱动程序的支持,我用它来避免每次测试运行时打开浏览器。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我只是使用了以下代码(使用 phantomjs 驱动程序,但我相信它也适用于 webkit):
PS 一年问题没有答案。他们应该给我徽章吗? :)
I just used the following code (with phantomjs driver, but I believe that it works with webkit also):
P.S. One year question without an answer. Should they give me a badge? :)
您应该使用
:focus
选择器,例如:You should use the
:focus
selector, e.g:使用 Selenium 驱动程序,您可以获得焦点元素:
然后您可以用它做您喜欢的事情
请注意,它返回一个
Selenium::WebDriver::Element
而find
返回一个Capybara::Node::Element
所以比较它们时要小心With the Selenium driver you can get the focused element:
Then you can do what you like with it
Note that it returns a
Selenium::WebDriver::Element
whereasfind
returns aCapybara::Node::Element
so be careful when comparing them2024 年 5 月更新:
方法 1(推荐为最具可读性):
水豚::选择器
。方法2:
另外,
Capybara::Selenium::FirefoxNode
似乎有focused?
方法,所以像这样使用 Firefox 驱动程序时应该可以:PS 这是上面代码的 Minitest 版本。我在 StackOverflow 上找不到任何关于它的问题,所以我把它留在这里,以防万一。
May 2024 update:
Method 1 (recommended as being the most readable):
Capybara::Selector
.Method 2:
Also,
Capybara::Selenium::FirefoxNode
seems to have thefocused?
method, so something like this should be possible when using Firefox driver:P.S. Here is the Minitest version of the code above. I couldn't find any question about it on StackOverflow, so I am leaving it here, just in case.