Skip to content

Instantly share code, notes, and snippets.

@jmgarnier
Created December 6, 2012 10:24
Show Gist options
  • Save jmgarnier/4223512 to your computer and use it in GitHub Desktop.
Save jmgarnier/4223512 to your computer and use it in GitHub Desktop.
How to unit test a presenter using rails i18n and ActionView helpers *without* loading the spec_helper, hence keeping the tests fast?
require 'action_view/helpers/number_helper'
require 'rails-i18n'
class FastPresenter
include ActionView::Helpers::NumberHelper
def initialize(value)
@value = value
end
def decorate
number_to_percentage @value, precision: 2
end
end
describe FastPresenter do
before do
load_rails_i18n :fr
I18n.default_locale = :fr
@presenter = FastPresenter.new 10
end
it "decorates as a percentage
with 2 digits after the decimal separator (locallized!)" do
expect(@presenter.decorate).to eq("10,00%")
end
# Helpers: move these to a support file
def load_rails_i18n(pattern)
RailsI18n::Railtie.add("rails/locale/#{pattern}.yml")
RailsI18n::Railtie.add("rails/pluralization/#{pattern}.rb")
RailsI18n::Railtie.add("rails/transliteration/#{pattern}.{rb,yml}")
RailsI18n::Railtie.init_pluralization_module
end
def load_rails_app_config_locales
# /!\ RAILS root is a relative path
rails_root = Pathname.new(File.expand_path("../../..", __FILE__))
I18n.load_path += Dir[rails_root.join('config', 'locales', '*.{rb,yml}')]
end
end
@pcreux
Copy link

pcreux commented Dec 6, 2012

I18n.load_path?

@jmgarnier
Copy link
Author

Benchmark

With spec_helper

time rspec spec/lib/fast_presenter_spec.rb
.

Finished in 0.05301 seconds
1 example, 0 failures

real 0m10.430s
user 0m7.715s
sys 0m1.579s

Fast tests

ruby-1.9.3-p327$ time rspec spec/lib/fast_presenter_spec.rb
.

Finished in 0.01953 seconds
1 example, 0 failures

real 0m1.323s
user 0m1.111s
sys 0m0.177s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment