Using the Draper Gem, Round One

Draper is a handy new gem for extracting
logic normally held in helpers and views into something Ruby developers love:
objects! Helpers are a great means to an end, but most of the time, our
helpers accept arguments, a great sign that the method is procedural instead
of being a method on the object we’re passing.

In my Intro to Test-Driven Rails
workshop
(which I’m holding September 17-18 in San Francisco and September 24-25 in
Boston), one of the apps we build is a simple todo tracker. I decided to try
out Draper in the codebase and see how things turned out; let’s dig in to some
code and see what it can do!

Fairly straightforward: we have completion_link, which either POSTs or DELETEs to /todos/:id/completion (adding or removing the timestamp of completed_at), and todo_state, which generates an HTML class for us.

The view shouldn’t be much of a surprise:

<%=link_to'Create a Todo',new_todo_path%><ulid='my-todos'><%@todos.eachdo|todo|%><liclass='<%=todo_statetodo%>'id='<%=dom_idtodo%>'><%=todo.description%><%=completion_linktodo%></li><%end%></ul>

As I mentioned above, helper methods that accept some instance of a model are
begging to be moved to an object that can instead be instantiated with that
model; in this case, a TodoDecorator.

This provides the flexibility of adding whatever markup within the <li>
while moving the logic for id/class generation (as well as the
complete/incomplete links) out of the helper. Now that I know the interface,
let’s write some tests.

First, require the correct file in the RSpec helper:

require'draper/test/rspec_integration'

To generate the decorator and its test, run:

rails generate decorator Todo

With that added, let’s test-drive the implementation. First, the list_item
method:

I test both complete and incomplete todos, ensuring that the text within the
block is present. Capybara.string makes it really easy to write assertions
against the generated markup.

Next, let’s test completion_link:

describeTodoDecoratordoincludeRails.application.routes.url_helperscontext'completion_link'doit'generates a link to complete the todo when incomplete'dotodo=build_stubbed(:todo)result=TodoDecorator.new(todo).completion_linkmarkup=Capybara.string(result)markup.shouldhave_css("a[data-method='post'][href='#{todo_completion_path(todo)}']",text: 'Complete')endit'generates a link to mark the todo as incomplete when complete'dotodo=build_stubbed(:todo,:completed)result=TodoDecorator.new(todo).completion_linkmarkup=Capybara.string(result)markup.shouldhave_css("a[data-method='delete'][href='#{todo_completion_path(todo)}']",text: 'Incomplete')endend# context 'list_item' ...end

This should look familiar since the majority of it came from the existing
helper. The biggest thing to note is accessing helper methods versus methods
on the decorated component. Helper methods are accessed by calling them on
h, which represents Rails’ helpers; this includes routes, record identifiers
(like dom_id), and tag generators (link_to, content_tag). Methods on
the decorated component (todo) can be invoked directly. Finally, if you don’t
want to prefix helper methods with h., just include Draper::LazyHelpers in
your decorator.

The view can now be changed to my desired implementation, and the suite is
still green! What are the benefits to a decorator versus leaving logic in the
view and helpers?

Logic is encapsulated: conditionals generating ids, classes, and markup
are now in one spot.

Code is object-oriented: things dealing with markup on a todo are
(surprise!) methods on our decorated todo instead of that procedural junk
we were using before.

Everything is more testable: because the view logic and helper logic is
rolled into one location, unit-tests for all of this are a breeze.
Acceptance tests are still important, but if we want to change the
structure or move forward with more data, it’ll be a relatively simple task.

I’ve only recently started playing with the draper gem but I really enjoy it.
The benefits are pretty clear to me and I love the fact that it’s so easily
testable. If you’ve got procedural code or logic in your views (or methods on
your models that are purely view-specific) I’d recommend moving those methods
to a better place: a decorator.

If you enjoyed this post, you might also like:

Want to level up your testing game?
Learn about testing Rails applications and TDD
in our new book
Testing Rails.
The book covers each type of test in depth,
intermediate testing concepts,
and anti-patterns that trip up even intermediate developers.