Close and Go BackBack to Viget

Helper Testing Independence

Brian Landau
Brian Landau, Web Developer, July 07, 2008 0

Testing helpers is a topic we’ve covered a couple times already here on the Viget Extend blog. I’ve additionally submitted a patch to Rails for adding some helper assertions to ActionView and other helper related testing goodness. But until that gets accepted and committed, I thought I’d hold everyone over with a helper testing plugin.

Independently Testing Helpers

The main tenet here is that helper functionality should be tested outside of another context (i.e. the controller). To achieve that, we need to create helper tests that live independent of our other tests. As Justin pointed out, Rails actually provides a class to assist in this, ActionView::TestCase.

The plugin I’ve created has two generators that help in creating these tests. The first, helper_tests, can be used to generate tests for your existing helpers. It creates a test file for each helper in the test/helpers directory and a test method for each public helper method. You can also pass it a list of helpers you wish to generate tests for and it will skip those that you don’t name.

Usage:

> script/generate helper_tests [SampleHelper Admin::AnotherHelper ...]

The other generator, helper, creates a helper -- and a helper test for the name provided. It will also accept a list of methods for the helper and generate them, as well as tests for each one.

Usage:

> script/generate helper HelperName [methods ...]

All generated helper tests will be run with rake test now along with all the other tests. Also a rake test:helpers task is provided to run just the helper tests.

Bonus Assertions!

That’s right ... I’ve also rolled in assert_tag_in, assert_tag_not_in, assert_select_in, assert_hpricot_in, and assert_hpricot_not_in assertions to the ActionView::TestCase class. These work exactly like their ActionController counterparts, except for the Hpricot ones, of course. These work by simply passing them the HTML string, and either a CSS selector or a XPath selector. The method then looks for an element matching the selector.

In the future, I’d like to spiffy assert_hpricot_in up by making it more like assert_select but it’s still useful to all Hpricot lovers out there as-is.

The Helper Me Test plugin:

The plugin is up on GitHub: http://github.com/vigetlabs/helper_me_test/tree/master

The clone URL to install with: git://github.com/vigetlabs/helper_me_test.git

As always comments, suggestions, or whatever are welcome, as well as forking it and adding your own twist.

Helpers vs. Partials - A Performance Question

Ben Scofield
Ben Scofield, Development Director, June 25, 2008 4

Have you ever looked in your development log and seen something like the following?

Processing FoosController#show (for ...) [GET]
  Session ID: BAh7CDoOcmV0dXJuX3R...
  SQL (0.000869) SHOW TABLES
  SQL (0.000931) SHOW TABLES
  Image Load (0.000465) SELECT images.* FROM ...
  [...]
Rendered entries/_detail (0.00221)
Rendered entries/_detail (0.00103)
Rendered entries/_detail (0.00118)
Rendered entries/_detail (0.00092)
Rendered entries/_detail (0.00107)
Rendered entries/_detail (0.00069)
Rendered entries/_detail (0.00215)
Rendered entries/_detail (0.00113)
Rendered entries/_detail (0.00113)
Rendered entries/_detail (0.00098)
Rendered entries/_detail (0.00098)
Rendered entries/_detail (0.00087)
Rendered entries/_detail (0.00079)
Rendered entries/_detail (0.00086)
Rendered entries/_detail (0.00079)
Rendered entries/_detail (0.00087)
Rendered entries/_detail (0.00076)
Rendered entries/_detail (0.00081)
Rendered shared/_nav (0.00207)
Rendered shared/_analytics (0.00011)
Rendered shared/_footer (0.00188)
Completed in 1.63867 (0 reqs/sec) | Rendering: 0.40653 (24%) ...

These sorts of entries in the log have always felt like a code smell to me - even when some sort of markup reuse is obviously necessary (so you can't just do it inline), I can't help but think that there's some significant cost to rendering the same file over and over again. So after a long time of thinking about it, I finally got around to doing some benchmarks comparing generating markup in a helper method, rendering a partial repeatedly for a collection, and rendering a partial with the :collection key. For each method, I use apache benchmark to hit a page 1000 times (with 2 simultaneous requests); each request generated 1000 divs like this:

<div>
  <span>index</span>
  <a href="#">link</a>
</div>

Here's what I found:

Method Time per Request    Requests/Second   
Helper 186.998 ms 10.70
Partial 438.244 ms 4.56
Partial for collection    266.068 ms 7.52

So it looks like there is a cost to rendering a partial repeatedly, but that cost can be reduced by using the :collection key, and reduced even further by generating the markup in a helper method. Of course, the helper method can be a smell of its own, but if performance is an issue it may be worth a look.

Note: This is an unscientific test, so feel free to respond with your own benchmarks.

Announcing the ActionButton Plugin

Brian Landau
Brian Landau, Web Developer, June 19, 2008 1

When creating web application there’s often a need for single links that have a destructive or “unsafe” effect. In accordance with HTTP specs, GET’s (e.g. links) should not be used for this. The issues that 37signals had with unsafe links prove the importance of this.

This is also important if your application is RESTful. Rails offers a few good solutions, but none of them are ideal. There’s link_to_remote, but this requires the user to have JavaScript enabled and doesn’t allow for progressive enhancement. Then there’s submit_to_remote, which requires you to wrap it in a form tag yourself and also doesn’t allow for progressive enhancement. Last, you have button_to, which is almost ideal, but it uses a submit button that offers less options for styling than a button tag.

And this is where the idea for a button tag helper came in. (See this blog post for a good description of why the button element rocks). Thus, ActionButton was born.

With it, you can create a form with a single button element. The form can be set to point to any url just as you would with a normal form. The button and the form can have different id and class attributes, making them easy to target via JavaScript. But you don’t need to set these; by default it will create classes and ids that are sensible. Of course, all the normal HTML options are available, too.

The plugin will also install a modified version of the lowpro library. The ujs_remote_form helper provided creates a snippet of lowpro JavaScript that can be used to make a form (or set of forms) submit via an AJAX call.

So how would I use this?

Well, if you have a list of blog posts in an admin section and you want to add delete buttons next to each of them and you want them to look the same in every browser, this is how you would do it.

<%= action_button 'delete_post', "#{image_tag('icons/delete.jpg', :alt => 'delete')} Delete", 
post_url(post), {:method => :delete, :number => post.id} %>

Then when you’re ready for some AJAXy goodness, you can either use the Rails built-in helper of the plugin’s lowpro one:

Built-in:

Add this for each post:

<%= observe_form "delete_post#{post.id}-form", :on => 'submit', 
:confim => 'Are you sure you wish to delete this post?' %>

Lowpro:

Add this for the whole page of posts:

<%= ujs_remote_form 'button.delete_post', :confirm => 'Are you sure you wish to delete this post' %>

So where do I get this plugin of button joy?

It’s up on github right now!

If you have any questions, comments or suggestions, send them my way. It’s great to get feedback, but if you really feel I messed something up, just fork it and make the changes you feel it needs.

First Hack Night a Success!

Patrick Reagan
Patrick Reagan, Development Director, June 19, 2008 6

We had about 10 people show up to Murky last night for a few hours of coding and conversation. Some ended up working on personal projects, others paired up to learn more about both the latest version of Passenger and JQuery. We finished up just in time to grab a few post-hack beers at Liberty Tavern across the street (not the coolest place, but it was close!).

We plan on doing this again soon. There's been talk of potentially moving it to Busboys & Poets in Shirlington, but Matt will post details about the next night as they're available.

Thanks to everyone who came out for making it a fun night!

Testing Helpers In Rails 2.1

Justin Marney
Justin Marney, Web Developer, June 17, 2008 3

The conventional approach to testing helpers in Rails has, until recently, always been relatively subjective. I have come across different strategies including generators, plugins and hand-hacked setups depending on where I looked. In sharp contrast, the controller testing convention has been DRY'd up and moved into the framework in the form of the ActionController::TestCase class. Fortunately, Brian has been working on some helper testing tools and recently stumbled across the ActionView::TestCase class. If you have been looking for a convenient, framework supported way to test your helpers, look no further. This class provides the same conventions as ActionController::TestCase and makes testing helpers a breeze.

Test Your Helpers Using ActionView::TestCase
Here is an example that shows how to use ActionView::TestCase along with Brian's assert_tag_in. First, create a test named HelperNameTest and inherit from ActionView::TestCase. Then just call your helper methods from your tests, it's that easy.

module ApplicationHelper
  def special_header()
    content_tag :div do
      link_to('Edit Profile', edit_account_path)
    end
  end
end

class ApplicationHelperTest < ActionView::TestCase
  def test_special_header_should_render_edit_link
    tag = special_header(:edit_profile => true)
    assert_tag_in(tag, :a, :attributes => {:href => edit_account_path})
  end
end

Worth noting here is the ability to test methods that rely on url_for without needing to create a temporary controller in your own testing code. I also want to point out that Chu Yeow did cover using ActionView::TestCase in his Living on the Edge series, but it totally slipped past me :)

Update

ActionView::TestCase is not loaded automatically. Be sure to require 'action_view/test_case' in your test_helper.

A Development Community for Viget Labs and Beyond

Every team member here at Viget Labs strives to be an innovator. We members of the development team are no different - that's why we're constantly engaging in community discussions and exploring the unknown that is the next generation of open-source web applications.

Viget Is Hiring!

Viget has job openings for Ruby Developers, Interns, and Front-End Developers. Learn More »

Recent Comments

I think that polymorphic_url(@commentable, :anchor => “comment_#{@comment.id}") should work. You can also refactor the “comment_#{@comment.id}” to a separated method, like dom_id, which returns the dom identifier of the comment.