Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub JavaScript delay in Capybara acceptance tests?

My Rails application includes a JavaScript modal that pops up 45 seconds after a user clicks on a link. As a result, my acceptance tests, which used to pass when there was no delay, are failing.

I originally tried to use the Timecop gem to fast-forward time in my Capybara acceptance test, but that did not work. When I added a sleep(45), however, that did work. Obviously, I can't have sleep(45) in my specs 3 times, but it's good to know what does work so I can get closer to that with a faster method.

What I've concluded from my experiments is that Ruby keeps track of time and Javascript keeps track of time and Timecop is fast-forwarding Ruby time but not Javascript time. Is there a way to fast-forward 45 seconds in my Capybara tests so that my Javascript event fires off?

Here is the function that is causing my tests to fail:

        $('.votable').one('click', '.vote', function() {
          $('.post-vote').
            delay(45000).
            queue(function() {
                $(this).dialog('open')
            });
        });

Again, when the delay is removed, my specs pass, but I need the delay. How can I stub this out in my Capybara tests? Or do I need to test the method with Jasmine?

like image 983
Jessie A. Young Avatar asked Mar 19 '13 01:03

Jessie A. Young


Video Answer


1 Answers

In the end, the simplest solution to this problem was to make my .js file a .js.erb file and then use branching to only include the delay in non-test environments. Not ideal, but all other solutions were much more involved and I was definitely not willing to slow my tests down by 45 seconds just to keep my view code looking pretty.

Final code looked like this:

$('.votable').one('click'). '.vote', function() {
  $('.post-vote').
   <% unless Rails.env.test? %>
     delay(45000).
   <% end %>
   queue(function() {
     $(this).dialog('open')
    });
 });
like image 118
Jessie A. Young Avatar answered Oct 21 '22 12:10

Jessie A. Young