Question

There's this nifty stackoverflow post on passing variables to Javascript. It echos this railscast episode. The technique works like a charm for configuring a jquery datepicker, but cause all my javascript integration tests to fail.

Here is the code in application.html.erb

<script type="text/javascript">
<%-# commented line -%>
  window.sDateFormatLocal = "<%= t 'date.formats.js_date' %>"
</script>

This is a datepicker initialization that uses it

  $("input.datepicker").datepicker({
    dateFormat: sDateFormatLocal,
    onClose: function(value, ui) {
     console.log("regular old datepicker");
    }
  }

It appears to work very well. The only problem, all my integration tests with 'js: true' now fail. Here are the errors I get.

Capybara::Poltergeist::JavascriptError: One or more errors were raised in the Javascript code on the page:

   ReferenceError: Can't find variable: sDateFormatLocal

When I run in browser (Chrome, Firefox) there are no errors or warnings in the console.

For completeness, a typical spec looks like this:

  describe "The root" do
    it "should load the page and have js working.", :js => true do
      visit root_path
      page.should have_content "Hello world"
    end
  end

Is there a setting I am missing to allow variables like this in poltergeist?

Was it helpful?

Solution 2

Just to follow-up on this, in case someone in is debugging a similar problem. It turned out in this case, not every view was using the same template. For instance, the signin screen has a different head. That was causing this not to load in certain circumstances, yet not others, like the ones where my tests were failing. Bottom line, make sure when you replicate your tests, you are doing it exactly as the tests do, like in my case, passing through a signin screen.

OTHER TIPS

If your datepicker function is not in jQuery document ready function or similar methods such as window.onload you'll have trouble.

By default the application.js will be loaded in head, and the JS code in your html.erb later. The html and assets are loaded by browser in parallel, and very likely assets will finish loading at first. If you execute the function right away instead of waiting for document ready, the variable is undefined.

If you missed that, put such code in ready block.

A better practice for exporting server variable is, instead of put it in html body, put it on head before application.js so you won't have any problem on undefined variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top