我有以下测试:
require "test_helper"describe ApplicationController do tests HomeController before do cookies[:locale] = "ru" request.headers["Accept-Language"] = "zh-cn,en-us" request.headers["CloudFront-VIEwer-Country"] = "FR" I18n.default_locale = :en end it "sets locale from URL params first" do get :index,locale: "de" I18n.locale.must_equal :de end it "sets locale from a cookie second" do get :index I18n.locale.must_equal :ru end it "sets locale from Accept-Language header third" do cookies.delete :locale get :index I18n.locale.must_equal :"zh-CN" end it "sets locale from CloudFront-VIEwer-Country header last" do cookies.delete :locale request.headers["Accept-Language"] = nil get :index I18n.locale.must_equal :fr endend
和相应的控制器:
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs,you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :set_locale def default_url_options(options = {}) { locale: I18n.locale }.merge options end private def set_locale I18n.locale = params[:locale] || cookies[:locale] || extract_locale_from_accept_language_header || set_locale_from_cloudfront_vIEwer_country || I18n.default_locale unless request.fullpath =~ /^\/(?:[a-z]{2,2})(?:[-|_](?:[A-Z]{2,2}))?/ redirect_to %(#{request.protocol}#{request.host}/#{I18n.locale}#{request.fullpath unless request.fullpath == "/"}),status: :found end end def extract_locale_from_accept_language_header if request.env["Accept-Language"] request.env["Accept-Language"].scan(/(?:[a-z]{2,2}))?/i).first end end def set_locale_from_cloudfront_vIEwer_country case request.env["CloudFront-VIEwer-Country"] when "FR" return :fr else return I18n.default_locale end endend
最后两个测试失败,因为Rails似乎没有识别我设置的http头变量,一切都落到了默认的语言环境:
Failure:ApplicationController#test_0004_sets locale from CloudFront-VIEwer-Country header last [/Users/aporter/Developer/com/wavetronix/www/test/controllers/application_controller_test.rb:33]Minitest::Assertion: Expected: :fr Actual: :enFailure:ApplicationController#test_0003_sets locale from Accept-Language header third [/Users/aporter/Developer/com/wavetronix/www/test/controllers/application_controller_test.rb:26]Minitest::Assertion: Expected: :"zh-CN" Actual: :en
如果我将Accept-Language更改为http_ACCEPT_LANGUAGE,那么该测试将通过.
根据Rails documentation,我的测试应该有效.我用几种不同的方式搜索这个问题寻找答案然后空洞. Stack Overflow上有一些与此类似的问题,但这些问题的答案和建议都没有解决我的问题.
我错过了什么?
环境:
> Mac OS X 10.11.1
> Ruby 2.2.2
> Rails 4.2.4
> minitest 5.8.0
>将标题转换为全部大写
>用下划线替换破折号
>前缀“http_”
因此,您可以在测试中设置request.headers [“Accept-Language”],并使用控制器中的request.env [“http_ACCEPT_LANGUAGE”]访问该值.同样,您在测试中设置request.headers [“CloudFront-VIEwer-Country”],并使用控制器中的request.env [“http_CLOUDFRONT_VIEWER_COUNTRY”]访问该值.
总结以上是内存溢出为你收集整理的ruby-on-rails – 最小的测试在Rails 4.2中使用自定义HTTP头失败全部内容,希望文章能够帮你解决ruby-on-rails – 最小的测试在Rails 4.2中使用自定义HTTP头失败所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)