Skip to content

Instantly share code, notes, and snippets.

@suchov
Last active April 11, 2017 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suchov/fa96d4be5a9d9f4cd233d939ab796877 to your computer and use it in GitHub Desktop.
Save suchov/fa96d4be5a9d9f4cd233d939ab796877 to your computer and use it in GitHub Desktop.
Don't use sleep or wait:
This breaks if we try to test via Capybara:
first(".modal-open").click
first(".confirm").click
It will click the button but the next interaction will fail because the modal hasn’t finished loading.
We could add a sleep here in the test but this would slow the test down a lot and won’t guarantee that the modal is loaded.
Luckily, Capybara provides some helpers for this exact situation.
Finders such as `first` or `all` return `nil` if there is no such element.
`find` on the other hand will keep trying until the element shows up on the page or a maximum wait time has been exceeded (default 2 seconds).
# this will take a few seconds to open modal
find(".modal-open").click
# this will keep trying to find up to two seconds
find(".confirm").click
Similar to find, most of Capybara’s matchers support waiting. You should always
use the matchers and not try to call the query methods directly.
# This will _not_ retry
expect(page.has_css?(".active")).to eq false
# This _will_ retry if the element isn't initially on the page
expect(page).not_to have_active_class
Remember, feature specs test the application from a user’s perspective.
As a user, I don’t care whether you use AJAX or not, that is an implementation detail.
Feature tests should assert on the UI only!
click_on "Save"
# This will automatically wait up to 2 seconds
# giving AJAX time to complete
expect(page).to have_css(".notice", text: "Document saved!)
Almost all AJAX interactions will change the UI in some manner for usability reasons.
Assert on these changes and take advantage of Capybara’s auto-waiting matchers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment