Created
December 6, 2012 10:24
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
I18n.load_path?