Refresh while waiting with RSpec+Capybara in a Rails project

This is some serious advanced stuff here. You should share it.

A colleague, looking at the git logs

I recently had to create a spec with Capybary+RSpec where I refresh the page and wait for a value to appear on this page. It this particular scenario there is no need for WebSockets or and JS. We just need to refresh the page.

But how to we test it?

# Expect that the new records page will show the correct value of the record
# We must do this in a loop as we are constantly refreshing the page.
# We need to stay here and refresh the page
# Use the Tmeout.timeout to stop the execution after the default Capybara.default_max_wait_time
Timeout.timeout(Capybara.default_max_wait_time) do
  loop do
    # Visit the page. If you visit the same page a second time
    # it will refresh the page.
    visit "/records"
    # The smart thing here is the wait: 0 param
    # By default find_all will wait for Capybara.default_max_wait_time as it is waiting for all JS methods 
    # to complete. But there is no JS to complete and we want to check the page as is, without waiting 
    # for any JS, because there is no JS. 
    # We pase a "wait: 0" which will check and return
    break if find_all(:xpath, "//a[@href='/records/#{record.to_param}' and text()='Continue']", wait: 0).any?

    # If we could not find our record we sleep for 0.25 seconds and try again.
    sleep 0.25

I hope it is helpful.

Want to keep it touch – find me on LinkedIn or Twitter.