Wait for Javascript and AJAX changes in Capybara

Recently I was having trouble with JS-enabled tests with Capybara on a Ruby on Rails app, when clicking stuff around and then asserting about content that was not on the page yet. I tried several solutions I found online, but either they were talking about wait_until, which is a method that's not available in Capybara anymore, or they just didn't work for me. Therefore, I decided to roll my own:
def wait_for
  Timeout.timeout(Capybara.default_wait_time) do
    loop until
      rescue MiniTest::Assertion

What this method does is wait for a few seconds for the assertions in the provided code block to run sucessfully. I use it by calling it with the assertion(s) I want to check on the page after a Javascript-related change, like so:
visit frontend_magazine_path(magazine_id: @magazine.id)

click_link 'Read latest issue'

wait_for do
  assert_equal "20 min left to read", page.find('#reader5-timer').text
Right now it's working pretty well, I was able to remove those pesky sleep n calls, and my tests feel sturdier and cleaner now.

1 comment: