An autocomplete is a nice example for an ajax driven feature and I will demonstrate how to test such a features with Rails 4 and Minitest.
First we will create a sample app and setup Minitest and Capybara for integration testing.
railsnewrails-autocomplete-test
We need to add `capybara` and the `poltergeist` driver to our Gemfile:
First we require the `capybara/rails` module than set the javascript driver to `poltergeist`. I am also setting the current\_driver of capybara to `nil` after each test because I want to use poltergeist only when we are testing javascript features so the rest of the test suite can run faster.
Than we make `ActiveRecord` to share the same connection between threads because capybara starts the browser in a different thread from the one our application uses and it wouldn't access to the same data in these threads. If you want to know more why we need do do this you can read Jose Valim's explanation on this link.
Now we have a setup to test our javascript features so let's write a test for an autocomplete form field.
We will expect a form with a search field on the root path:
1) Error:
AutocompleteTest#test_autocomplete:
Capybara::ElementNotFound: Unable to find field "search_keyword"test/integration/autocomplete_test.rb:8:in `block in <class:AutocompleteTest>'
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
Let's fix this and generate a controller with an action and add the missing form to the view. We also need to set the root of our application to that action:
Now our test is passing. Next step is to extend our test to fill the form with something and see the autocomplete with some suggestion. Before we go any further we need to decide which javascript library to use as we need to know the markup it will use. I chose twitter's typeahead for this tutorial. We can copy the typeahead.js to the vendor/assets/javascripts folder and than we just need to require it in the application.js file:
It means we need to look for a div.tt-suggestion element after we entered the text to the field and compare the text of the element with the desired string:
After we filled in the field we need to trigger the `focus` event.
Of course this test fails in the moment so let's make it pass.
First step is to setup a route and an action for the source of the suggestions:
Now if we run the test it will pass.
I hope you learned how to test your javascript features with capybara and minitest.
You can view the code of the sample application on this link.