Update: While this technique is useful when you actually need to bind a template to your helper test, most of the time you can simply stub the helper right there, using something like stub(self).t('.title') { "Title" }
Once on a beautiful day the sun was shining and the room was full of pleasant warmth. I was whistling a tune happily to myself while writing the following rails helper.
content_for(:title) { t('.title', :default => page_title) }
@show_title = show_title
end
It’s so neat and simple. It allows you to write title "English Title" and provides a way to override title with translation scoped like pages.index.title.
Then came the test (apologies, TDD purists). Whistling along with the chirping birds I put the following in my helper test.
class LayoutHelperTest < ActionView::TestCase
context "#title helper" do
should "create content for title" do
title("foobar")
assert_equal "foobar", @content_for_title
end
end
end
Suddenly the birds went silent. The room got colder and darker. I got an error.
Here’s what happened. Using scoped translations such as t('.title') requires a template. It makes perfect sense because scope can only be looked up for a particular template’s path. After some research I found that it’s quite easy to stub a template for tests to work. You can put something like this in your setup method.
# Easy to convert to equivalent in mocha/flexmock/etc.
stub(self).template { ActionView::Template.new "app/views/index.html.haml" }
This is the kind of usefulness that could easily be made into a helper. You can put this in your test_helper.rb.
stub(self).template { ActionView::Template.new File.join("app", "views", path) }
end
Now my test looks very neat.
class LayoutHelperTest < ActionView::TestCase
context "#title helper" do
setup do
use_template "pages/index.html.haml"
end
should "create content for title" do
title("foobar")
assert_equal "foobar", @content_for_title
end
end
end
Running tests… Green! And birds are back!
[...] Testing Helpers That Use Scoped Translations | Medium eXposure mediumexposure.com/2009/11/02/testing-helpers-use-scoped-translations – view page – cached I’m Maxim Chernyak aka Hakunin. Every day I deal with three technologies – Ruby on Rails, Drupal, and Zend Framework. I deal and I blag. Natalie is my fiancée and I love her. — From the page [...]