Skip to content

Instantly share code, notes, and snippets.

@matthieuprat
Created October 7, 2016 14:49
Show Gist options
  • Save matthieuprat/092022af6df09d0f68cada10a5687f09 to your computer and use it in GitHub Desktop.
Save matthieuprat/092022af6df09d0f68cada10a5687f09 to your computer and use it in GitHub Desktop.
Capybara eventually helper
def eventually(timeout: Capybara.default_max_wait_time, interval: 0.2)
Timeout.timeout(timeout) do
begin
next yield
rescue Minitest::Assertion, Capybara::ExpectationNotMet
sleep interval
retry
end
end
rescue Timeout::Error
yield
end
@seanabrahams
Copy link

If you're using RSpec you'll want to add RSpec::Expectations::ExpectationNotMetError to the exception list.

def eventually(timeout: Capybara.default_max_wait_time, interval: 0.2)
  Timeout.timeout(timeout) do
    begin
      next yield
    rescue RSpec::Expectations::ExpectationNotMetError, Minitest::Assertion, Capybara::ExpectationNotMet
      sleep interval
      retry
    end
  end
rescue Timeout::Error
  yield
end

Also, in case it helps others, I've placed this method inside of a file located at spec/support/helpers/capybara.rb and wrapped it in module Helpers:

module Helpers
  def eventually(timeout: Capybara.default_max_wait_time, interval: 0.2)
    Timeout.timeout(timeout) do
      begin
        next yield
      rescue RSpec::Expectations::ExpectationNotMetError, Minitest::Assertion, Capybara::ExpectationNotMet
        sleep interval
        retry
      end
    end
  rescue Timeout::Error
    yield
  end
end

If your rails_helper.rb or spec_helper.rb is already set to autoload everything in spec/support then eventually is ready to be used in your specs.

scenario "User creates a new post" do
  visit "/posts/new"
  expect(page).to have_text('Title')
  fill_in("title", with: "New Title")
  click_on('Save')
  eventually {
    expect(page).to have_text('Success')
  }
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment