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
      begin
        yield
      rescue MiniTest::Assertion
      end
  end
  yield
end

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
end
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.

3 comments:

  1. Thanks to share these details it’s truly nice.
    http://mediaonlines.com/

    ReplyDelete
  2. It’s true that SEO results aren’t instant. And it’s for that reason that at AIM we always say: SEO is a marathon, not a sprint.
    xenforo config.php

    ReplyDelete
  3. Personally I think overjoyed I discovered the blogs.
    Sex Toys

    ReplyDelete