Capybara tests - alternative to sleep

I’ve been trying to find alternatives to using sleep for some time and it seems that every single suggested method to avoid using sleep never works and I’m at the end of my rope.

      it 'finds the correct product when searching by job type', js: true do
        fill_in('filterrific_for_work_type', with: 'Central')
        # once again, sleep feels like the only thing that works
        #sleep 1 # TODO: find a better way..
        expect(find('#work_queue_items_filter_reset')).to have_content('Reset All Filters')
        expect(page).to have_link('IP Central Report',
                                  href: work_queue_item_path(@release.id))
      end

I also have this wait for ajax helper:

module CapybaraHelpers
  def wait_for_ajax
    Timeout.timeout(Capybara.default_max_wait_time) do
      loop until finished_all_ajax_requests?
    end
  end

  def finished_all_ajax_requests?
    page.evaluate_script('jQuery.active').zero?
  end
end

And in spec_helper.rb:

RSpec.configure do |config|
config.include CapybaraHelpers, type: :feature
End

This test breaks unless I add the sleep 1. and I’ve tried so many iterations using things like ‘within’ ‘find’, ‘have_content’ etc. This is really driving me crazy.

1 Like

It appears you need to break this down into more than one test.
Whenever you write a test it should always provide predictable behavior. If you are testing the UI response then mock out any external service and focus on testing the UI.

If you are testing the response of an external service then use a Unit test rather than this Integration test.

I don’t know how I’d break this in to more than one test? It’s so simple, fill in an input field which fires off a $('#filterrific_filter').on( "change", ":input", Filterrific.submitFilterForm );

and then test for the results

Also, this is testing a very javascript heavy interface and I feel a feature test is, by far the best way to go. Everyone says how bad using sleep is in Capybara test, and here’s an instance where I’d love to find a way to not use sleep.

This test is testing for the correct filtering of a collection of database associations. The strange thing is that, with sleep, the collection is able to be displayed and the individual rows are able to display their proper db associations. For instance, on this line in the view:

<%=link_to(wqi.workable.getType, work_queue_item_path(wqi)) %>,

the wqi.workable is not nil. Without sleep the wqi.workable is nil so it’s a race condition between Capybara testing for elements and the collection fully having time to process it’s dependencies

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.