【问题标题】:Rails I18n locale routing and RSpec testingRails I18n 语言环境路由和 RSpec 测试
【发布时间】:2012-02-08 02:29:28
【问题描述】:

我的申请是用英文写的,一切都很好。昨天我开始使用 Rails.I18n 国际化支持。这一切都很好。当我浏览 http://localhost:3000/jp/discounts 时,它是日文的,并且“http://localhost:3000/discounts”给了我默认的英文语言环境(当没有指定语言环境时)。

这是我的 route.rb,如您所见,管理命名空间未本地化:

scope '(:locale)' do
  resources :discounts do
    resource :map, only: :show
    collection do
      get :featured_city
    end
  end
end
namespace :admin do
  resources :users do
    collection do
      get :members
      get :search
    end
  end
end

但是我的 RSpec 开始失败。

Failure/Error: it { should route_to('admin/users#edit', id: '1') }
The recognized options <{"action"=>"edit", "controller"=>"users", "locale"=>"admin", "id"=>"1"}> 
  did not match <{"id"=>"1", "controller"=>"admin/users", "action"=>"edit"}>, 
difference: <{"controller"=>"admin/users", "locale"=>"admin"}>.
  <{"id"=>"1", "controller"=>"admin/users", "action"=>"edit"}> expected but was
  <{"action"=>"edit", "controller"=>"users", "locale"=>"admin", "id"=>"1"}>

admin相关的测试都有这种问题。我该如何解决这个问题?它在开发中运行良好。

以下是其他与语言环境相关的代码:

application_controller.rb

  def default_url_options
    { locale: I18n.locale }
  end

config/initializers/i18n.rb

#encoding: utf-8
I18n.default_locale = :en

LANGUAGES = [
  ['English', 'en'],
  ["Japanese", 'jp']
]

【问题讨论】:

  • 如果将namespace :admin 块移到scope 块上方会发生什么?
  • 谢谢!它消除了大部分错误(剩下的一个是另一个问题)。但是我不明白这背后的机制,因为我的范围如何影响它之外的东西?你能写下答案吗?可以解释一下吗?

标签: ruby-on-rails internationalization rspec rspec2


【解决方案1】:

当 Rails 尝试将给定 URL 与路由匹配时,它会从 config/routes.rb 文件的顶部开始,并在它认为匹配的第一个路由处停止。由于在您最初的问题中,您首先使用了 scope 块,因此 Rails 认为您的 /admin URL 指示了带有 :locale =&gt; 'admin' 的路由。

您需要 Rails 以匹配以 /admin 开头的路径到您的管理命名空间。通过将它放在你的路由文件中,你会导致 Rails 在找到匹配项后“停止查找”。

这是过于简单化了,但我希望它会有所帮助。

如果您还没有,也请查看the Rails routing guide

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多