Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cucumber: Wait for ajax:success

I have the following typical cucumber steps in a Rails 3.1 project:

...
When I follow "Remove from cart"
Then I should see "Test Product removed from cart"

The difficulty is that "Remove from cart" button is an ajax :remote call, which returns "Test Product removed from cart" to the #cart_notice element via:

$('#cart_notice').append("<%= @product.name %> removed from cart");

The function works fine in the browser, but doesn't find the "Test Product removed from cart" text in cucumber. I'm guessing this is because Cucumber is searching for the text before the AJAX returns it?

So, in short...how do I ensure cucumber waits for the ajax to return a result before searching for the desired content?

like image 510
PlankTon Avatar asked Sep 02 '11 16:09

PlankTon


1 Answers

To add to what dexter said, you may want to write a step that executes JS in the browser which waits for ajax requests to finish. With jQuery, I use this step:

When /^I wait for the ajax request to finish$/ do
  start_time = Time.now
  page.evaluate_script('jQuery.isReady&&jQuery.active==0').class.should_not eql(String) until page.evaluate_script('jQuery.isReady&&jQuery.active==0') or (start_time + 5.seconds) < Time.now do
    sleep 1
  end
end

You can then include the step as needed, or after every javascript step:

AfterStep('@javascript') do
  begin
    When 'I wait for the ajax request to finish'
  rescue
  end
end

I was having issues with the automatic synchronization, and this cleared it up.

like image 80
jcnnghm Avatar answered Oct 19 '22 22:10

jcnnghm