Dave Morse
Dave Morse

Reputation: 757

How to force scripts to load before interpreting html in Rails Capybara JS tests

In my file dances.html.erb, my test complains:

Failures:

  1) Creating dances creates a new dance with non-javascript data
     Failure/Error: visit '/dances/new'

     Capybara::Poltergeist::JavascriptError:
       One or more errors were raised in the Javascript code on the page. If you don't care about these errors, you can ignore them by setting js_errors: false in your Poltergeist configuration (see documentation for details).

       ReferenceError: Can't find variable: $
       ReferenceError: Can't find variable: $
           at http://127.0.0.1:33842/dances/new:81 in global code

I think the offending html code looks like

<script>

  $( "#choreographer-autocomplete" ).autocomplete({
    source: <%= a_to_safe_str(Choreographer.all.map &:name) %>,
    autoFocus: true,
    minLength: 0
  });
  $( "#start-type-autocomplete" ).autocomplete({
    source: ["improper","Becket","Becket ccw","four face four","square dance","indecent"],
    autoFocus: true,
    minLength: 0
  });
</script>

and the offending calls to '$' are here. I think this means JQuery isn't loading? If I snip them, then the next error is:

 Failure/Error: JSON.parse self.figures_json

 ActionView::Template::Error:
   784: unexpected token at '{{toJson(figures.arr)}}'

Those handlebars are an Angular thing. Is Angular also not loading?

Here's my Rails application.js:

//= require angular
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require_tree .

//= require jquery-ui/autocomplete
//= require angucomplete-alt

This works fine in the Real World, just not in this test.

Is there something I need to do to get these JS libs to load before the body html is executed?

Upvotes: 0

Views: 575

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49870

Since you are running the latest PhantomJS the most likely cause is that you have an error in one of your JS files. A big difference between the dev and test environments is that in the test environment rails concatenates all your JS files together. This means that an error in one file can prevent the rest of the JS from being processed. In dev mode they're all separate so an error in one doesn't stop the others from being processed. Check your browsers console log for errors and make sure they are fixed.

Upvotes: 1

Related Questions