'NoMethodError: undefined method `scan' for nil:NilClass' 使用 rails 进行功能测试时

Off*_*eYA 4 ruby ruby-on-rails functional-testing

这不是问题,而是我找到的解决方案。

我正在使用 Ruby on Rails 4.1 开发一个应用程序,该应用程序以西班牙语、英语和日语显示文本。

当我开始功能测试时,我不断收到以下错误:

NoMethodError: nil:NilClass 的未定义方法“扫描”

冲浪我看到几个帖子有同样的错误,但没有一个对我有用。

这是代码原始代码:

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
Run Code Online (Sandbox Code Playgroud)

所以这是/test/controllers/homes_controller_test.rb的代码:

require 'test_helper'

class HomesControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
  end
end
Run Code Online (Sandbox Code Playgroud)

所以,当我'rake test'时,我得到:

  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>'
Run Code Online (Sandbox Code Playgroud)

eng*_*nky 5

以下解决方案也可以在没有开始救援块的情况下工作

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

或者

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
Run Code Online (Sandbox Code Playgroud)