Simulating a keypress using capybara-webkit in rails
-
15-11-2019 - |
Question
I'm using capybara-webkit to test a form where the fields are populated using jquery-tokeninput (https://github.com/loopj/jquery-tokeninput). The problem is that using fill_in does not work with this. Is there anyway to test this automatically? Thanks in advance.
Solution
https://github.com/markgandolfo/send-keys
Send the 'a' character to the input who's id is search (#search)
And I send a to "input#search"
Send the 'a', 'b' and 'c' characters to the input who's id is search (#search)
And I send abc to "input#search"
You can put them in quotes if you feel more comfortable
And I send 'abc' to "input#search"
You can also send modifier/special key strokes to an element
And I send arrow_left to "input#search"
You can even send a combination of modifier and characters
This will result in a the character 'A' being sent to the input
And I send [shift, a] to "input#search"
Or maybe you just want to press enter
And I send enter to "input#search"
How cool would it be to test the counter in a text area (say for a twitter app)
And I send hello to "#message" And I should see "135" in "characters_left" And I send backspace to "#message" And I should see "136" in "characters_left"
We used it to test completion suggestions
The first suggested name was highlighted and responded to an enter keypress
And I send "bo" to "input#username" And I should see "bob" within "username_suggestions" And I send enter to "input#username"
OTHER TIPS
I have been using token input also, and what it does is that it hides your actual input field, and replaces it with another element with an id matching token-input-{your_field_id}
. So say you have a field with the id search
, you should in fact target the element with the id token-input-search
.
So an example code snippet would be:
fill_in "token-input-search", with: "hello"
And you can test you behaviour afterwards.
From the release notes in the capybara-webkit code, they have this entry from the 1.0.0 release:
* Set text fields using native key events.
So, it looks like setting the text on the text field is going to cause the native events to fire.
Like you, I also needed this to work and found that this did the trick:
find('input#query').set 'some text'
My javascript picked up the keyup
event that it was listening for and fired the way it should.