views:

28

answers:

1

So in my Rails application, I'm trying to set up Javascript testing on certain views.

Right now, I'm doing this by having a conditional in each view..

<% if AppConfig['js_testing'] %>
<script>
...
</script>
<% end %>

If I have it on each page, there's a lot of code duplication. Is there a way manage everything from the application layout?

A: 

There's a few places you can put this that will help reduce duplication. The main layout is an ideal candidate. Another possibility is a helper method that's a lot easier to introduce.

You could also define a conditional javascript_tag helper method that will only introduce the JavaScript if your trigger is set. Usually this is along the lines of:

def javascript_testing_tag(content)
  AppConfig['js_testing'] ? javascript_tag(content) : ''
end

Then it's a pretty straightforward exercise to wrap all your test scripts with that conditional. It will make it easier to refactor things later should the logical trigger for this behavior change.

The optimal implementation depends on what kind of scripting content you're introducing. If it's tied closely to the JavaScript that may be on a particular view, you may be stuck doing this.

An alternative is to simply tag each page and have a testing JavaScript harness that will trigger specific behavior depending on the structure of the document. For example, if there's an element div#user_list you might run testUserList().

It is then trivial to simply not include the testing JavaScript file in non-testing environments.

tadman
Yes, I'm planning to use a test suite like YUITest and all of the test cases should be specifically tailored to the javascript on each page. So maybe I am stuck. Thanks!
Alex
As a follow up, is it possible for me to put something in the application layout so that it can check what page is being rendered?
Alex
You can always check params[:controller] and params[:action] to do whatever you need.
tadman