'NoMethodError: undefined `scan' method for nil: NilClass' during functional testing with rails

This is not a question, this is the solution I found.

I am developing a Ruby on Rails 4.1 application that displays text in Spanish, English, and Japanese.

When I started functional testing, I keep getting the following error:

NoMethodError: undefined `scan 'method for nil: NilClass

Surffing I saw several posts with the same error, but no one works for me.

This is the source code of the 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>'
+4
source share
2

def extract_locale_from_accept_language_header
   accept_language = (request.env['HTTP_ACCEPT_LANGUAGE'] || 'es').scan(/^[a-z]{2}/).first
end

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
+3

, application_controller.rb extract_locale_from_accept_language_header . lananguage .

:

  def extract_locale_from_accept_language_header
    begin
      request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
    rescue
      'es'
    end
  end

, .

+1

Source: https://habr.com/ru/post/1540570/


All Articles