![](/img/trans.png)
[英]"NoMethodError: undefined method `env' for nil:NilClass" for Helper testing in rails
[英]'NoMethodError: undefined method `scan' for nil:NilClass' when functional testing with rails
這不是一個問題,它是我找到的解決方案。
我正在使用Ruby on Rails 4.1開發一個應用程序,它以西班牙語,英語和日語顯示文本。
當我開始功能測試時,我不斷收到以下錯誤:
NoMethodError:nil的未定義方法`scan':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
所以,當我'參加考試'時,我得到了:
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>'
以下解決方案也可以在沒有開始救援塊的情況下工作
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是令人費解的。 它沒有從請求中獲取lananguage標頭。
所以我把它改成:
def extract_locale_from_accept_language_header
begin
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
rescue
'es'
end
end
我希望你發現這很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.