Reputation: 735
This is not a question, it a solution that I found.
I am developing an application with Ruby on Rails 4.1 that displays text in Spanish, English and Japanese.
When I started the Functional Testing, I keep getting the following error:
NoMethodError: undefined method `scan' for nil:NilClass
Surffing I saw several posts with the same error, but none work for me.
This is the code original code:
application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
navegador = extract_locale_from_accept_language_header
ruta = params[:locale] || nil
unless ruta.blank?
I18n.locale = ruta if IDIOMAS.flatten.include? ruta
else
I18n.locale = navegador if IDIOMAS.flatten.include? navegador
end
end
private
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
def ajusta_pagina_filtro
if defined? params[:post][:filtrar_por]
buscar = params[:post][:filtrar_por]
else
buscar = ''
end
page = params[:pagina] || 1
[page, buscar]
end
end
So this is the code for /test/controllers/homes_controller_test.rb at:
require 'test_helper'
class HomesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
end
So, when I 'rake test', I got:
1) Error:
HomesControllerTest#test_should_get_index:
NoMethodError: undefined method `scan' for nil:NilClass
app/controllers/application_controller.rb:22:in `extract_locale_from_accept_language_header'
app/controllers/application_controller.rb:9:in `set_locale'
test/controllers/homes_controller_test.rb:5:in `block in <class:HomesControllerTest>'
Upvotes: 4
Views: 4272
Reputation: 29318
The following solutions will also work without a begin rescue block
def extract_locale_from_accept_language_header
accept_language = (request.env['HTTP_ACCEPT_LANGUAGE'] || 'es').scan(/^[a-z]{2}/).first
end
Or
def extract_locale_from_accept_language_header
return 'es' unless request.env['HTTP_ACCEPT_LANGUAGE']
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
Upvotes: 5
Reputation: 735
The problem whas that at application_controller.rb, the method extract_locale_from_accept_language_header is failling. It is not getting the lananguage header from the request.
So I change it to:
def extract_locale_from_accept_language_header
begin
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
rescue
'es'
end
end
I hope you find this usefull.
Upvotes: 1