Understanding native and send_keys in Capybara

痞子三分冷 提交于 2019-12-23 15:35:57

问题


I am trying to understand the meaning of the following Capybara syntax. What exactly does native do? What is send_keys used for? Also, I would like to understand what this particular block does.

within('#step-3') do
 recipe_name = first(:xpath, '//*[@id="recipe-name"]').native
 recipe_name.clear
 recipe_name.send_keys('Email recipe')
end

回答1:


Capybara uses a driver to control a browser or browser simulator (Rack::Test, Poltergeist, Selenium, etc.). Each driver must implement the API that Capybara defines. That API includes the Element class and its .native method. .native returns the object that the driver uses internally to represent a DOM element. Capybara itself doesn't have any use for that object, but some drivers' implementations of that object have driver-specific methods that can be useful in tests.

.clear and .send_keys are, then, driver-specific methods on the DOM element whose CSS selector is #recipe-name. Presumably it is an element that the user types into. We can probably guess what .clear does. .send_keys tells the element that the user has pressed each of the keys in the given string in order.

The point of using .send_keys rather than just doing fill_in '#recipe-name' with: 'Email recipe' is that some browser behavior, such as Javascript events, only happens when the user presses a key. Apparently fill_in puts text into the element in a way that doesn't make the browser think that any keys have been pressed. So if you're testing something that cares about keypress events, you need to use .send_keys.

I gave an example of using .send_keys in my answer to a question about testing a jQuery autocomplete field.



来源:https://stackoverflow.com/questions/25651393/understanding-native-and-send-keys-in-capybara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!