Search code examples
jqueryruby-on-railscoffeescriptjasminejasmine-jquery

How to load Rails view for testing in Jasmine?


The following code works in a browser, but how to test it with Jasmine? Upon clicking #opener, it should display a jQuery dialog box and make an ajax call to load the content:

$ ->
  $( "#dialog" ).dialog({ autoOpen: false });
  $( "#opener" ).click ->
    $( "#dialog" ).dialog( "open" );
    $( "#dialog" ).load('/content');

spec.js.coffee:

describe "Open Dialog Box", ->
  it "gets content from server", ->
    spyOn($, "ajax")
    $('#opener').click()
    expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/content")

view:

<div>
  <a id="opener" href="#">See Content</a>
</div>

<div id="dialog" title="Content"></div>

It is not getting the click event, so it seems that the view is not being loaded. How to load the view for testing?

Working in Rails 3.2.2 and Jasminerice.


Solution

  • Jasminerice allows any template put inside spec/javascript/fixtures to be treated as a fixture. You just need to execute loadFixture 'fixtureName'. Fixture documentation for Jasminerice explains a bit more.

    I would not go with rendering the same views as in app/views. If you're doing it right, you're be only depending on minor structure (classes, etc) that you can easily replicate in a fixture. If you then need to check that your actual views comply with these assumptions, you can write a request spec (sadly, rspec views spec default matchers cannot check document structure, though you can always rely on some nokogiri-fu for that.

    If you have some partials, you can rely on Jasminerice::HelperMethods to provide some methods/variables.