'NoMethodError:使用rail进行功能测试时,未定义的方法'scan'for nil:NilClass'



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

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

当我开始功能测试时,我一直得到以下错误:

NoMethodError:未定义的方法' scan' for 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
这是/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

所以,当我'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>'

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

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

问题在于application_controller。Rb ,方法extract_locale_from_accept_language_header失败。它没有从请求获取语言头。

所以改成:

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

最新更新