Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better alternative to using sleep in Capybara?

In my test I have a step where I fill out a field and press enter. This field then returns a result set on the next page.

Here is my helper method:

def search(term)
  fill_in('query-text', :with => term)
  click_button('search-button')
end

After that I have a step that simply says:

page.should have_content(tutor)

However, the issue is that even though the page after my page loads with the results, the step after it passes even if it should be false. I have set a debugger in the step and when I manually check it, the assertion fails as I expect it too. My assumption is that the the next step is checking before the page even reloads. I placed a sleep at the end of my search method to make it look like:

def search(term)
  fill_in('query-text', :with => term)
  click_button('search-button')
  sleep 5
end

But I feel like using sleep is a hacky way to resolve this issue. I am using Capybara 2 so the use of wait_until is removed. Is there a better way to handle this issue rather than relying on sleep?

like image 414
JustNeph Avatar asked Jan 16 '13 22:01

JustNeph


2 Answers

Do you have tutor text in your HTML page hidden? has_content? returns true for any text present in html, including hidden text which is not visible. So I would rather replace it with expect(page).to have_text(tutor), which checks only for visible text on a page. .text is also pretty slow method, so these extra split seconds may be handy for you.

Another approach is to restore wait_until method in your spec helpers, since it's really handy in most cases:

def wait_until(timeout = DEFAULT_WAIT_TIME)
  Timeout.timeout(timeout) do
    sleep(0.1) until value = yield
    value
  end
end

In any case it will be better than waiting for a fixed timeout each time.

like image 156
nattfodd Avatar answered Oct 14 '22 03:10

nattfodd


This test passes as tutor is already present on the page.

So you should check not for tutor but for something else, e.g. for element with text tutor that is present only after page reload.

like image 38
Andrei Botalov Avatar answered Oct 14 '22 02:10

Andrei Botalov