我已在application.rb
中覆盖了方法default_url_optionsclass ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
def redirect_to_root
redirect_to root_path
end
private
def default_url_options(options={})
{ locale: I18n.locale }.merge options
end
def set_locale
if params[:locale].blank?
logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
abbr = extract_locale_from_accept_language_header
I18n.locale = if Language.find_by(abbr: abbr).nil?
logger.debug "* Unknown Language"
I18n.default_locale
else
abbr
end
logger.debug "* Locale set to '#{I18n.locale}'"
else
I18n.locale = params[:locale]
end
end
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
end
效果很好。 但是当我启动控制器测试时,它们都会失败。例如:
it "renders show template" do
get :show, id: @book.id
expect(response).to render_template :show
end
ActionController::UrlGenerationError:
no route matches {:action=>"show", :controller=>"books", :id=>"1"}
为什么rspec没有传递我在ApplicationController中设置的defautl url选项(语言环境)?如何告诉rspec这样做?
答案 0 :(得分:1)
我有一个类似的问题,但测试了一个ActionMailer类。它不是ActionController,因此未调用default_url_options
。
我必须在配置中配置默认语言环境:
# config/environments/test.rb
Rails.application.configure do
# ...
config.action_mailer.default_url_options = {:host => 'localhost:3001', :locale => :de}
end
也许您的配置中有一条类似的行会覆盖url_options
。