Skip to content

Asynchronous Javascript drivers

jferris edited this page Feb 22, 2012 · 1 revision

When using an asynchronous Javascript driver, such as Selenium or capybara-webkit, you'll need to make sure your test assertions wait until the server is finished processing each request. Here's a quick example:

visit "/posts/new"
fill_in :title, :with => "Hello"
click_button "Create Post"
Post.last.title.should == "Hello"

This test will fail most of the time, because the request will still be processing by the time the test looks for a Post. You can use capybara's wait_until method to wait until the Post is created:

visit "/posts/new"
fill_in :title, :with => "Hello"
click_button "Create Post"
wait_until { Post.count == 1 }
Post.last.title.should == "Hello"

Better yet, you can use built-in capybara matchers and query methods to check that the UI changes to reflect the new post. In addition to checking something that's of actual value to the user (useful in an acceptance test), you won't have to worry about syncing up the test with server requests, because the built-in matchers automatically wait until the request is finished:

visit "/posts/new"
fill_in :title, :with => "Hello"
click_button "Create Post"
visit "/posts"
page.should have_content("Hello")

See the capybara documentation for more information about wait_until.

Clone this wiki locally