JustNeph
JustNeph

Reputation: 781

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?

Upvotes: 11

Views: 14474

Answers (3)

nattfodd
nattfodd

Reputation: 1890

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.

Upvotes: 5

Andrei Botalov
Andrei Botalov

Reputation: 21096

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.

Upvotes: 1

Dmitriy Konovalov
Dmitriy Konovalov

Reputation: 227

yes, you're right wait_until is removed, new method is #synchronize, but I don't know for now how to use it:)

look into

http://www.elabs.se/blog/53-why-wait_until-was-removed-from-capybara

https://github.com/jnicklas/capybara/blob/master/lib/capybara/node/base.rb#L44

Upvotes: 0

Related Questions