【问题标题】:Rspec with I18nRspec 与 I18n
【发布时间】:2016-10-10 09:22:14
【问题描述】:

我正在尝试测试包含一些 I18n 的现有应用

这是我的测试:

require "spec_helper"
require "rails_helper"

describe "visiting landing page" do
  it "should display the welcome text" do
    visit root_path
    expect(page).to have_text("TUTOS DUCLOS")
  end
end

我有以下错误:

Failures:

  1) visiting landing page should display the welcome text
     Failure/Error: visit root_path

     ActionController::UrlGenerationError:
       No route matches {:action=>"landing", :controller=>"home"} missing required keys: [:locale]
     # ./spec/features/home_spec.rb:8:in `block (2 levels) in <top (required)>'

Finished in 0.00127 seconds (files took 1.89 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/features/home_spec.rb:7 # visiting landing page should display the welcome text

如果我更改root_pathin "en"测试通过...但我不确定这样做是否正确... 有没有更传统的轨道? 谢谢

编辑

这是我的路线:

Rails.application.routes.draw do

  scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
    get "/best_voted", to: "tutos#best_voted"
    resources :tutos
    namespace :users do
      resources :tutos
    end

    resources :tutos, only: [:show]

    resources :tutos do
      member do
        put "like", to: "tutos#upvote"
      end
    end

  as :user do
    get     "/register",  to: "devise/registrations#new", as: :register
    get     "/login",     to: "devise/sessions#new", as: :login
    get     "/logout",    to: "devise/sessions#destroy", as: :logout
    get     "/account",   to: "users#show", as: :account
    get     "/login" ,    to: "devise/sessions#new", as: :new_user_session
    post    "/login" ,    to: "devise/sessions#create", as: :user_session
    delete  "/logout" ,   to: "devise/sessions#destroy", as: :destroy_user_session
  end

    devise_for :users, skip: [:sessions]

    resources :users

    root "home#landing"
  end
  get '*path', to: redirect("/#{I18n.default_locale}/%{path}")
  get '', to: redirect("/#{I18n.default_locale}")
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rspec


    【解决方案1】:

    您可以在路由中将语言环境声明为可选参数:

    # config/routes.rb
    scope "(:locale)", locale: /en|fr/ do
      resources :books
    end
    

    class ApplicationController < ActionController::Base
      before_action :set_locale
    
      private
    
        def set_locale
           I18n.locale = params[:locale] || I18n.default_locale
        end
    end
    

    【讨论】:

    猜你喜欢
    • 2012-10-09
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 2016-03-07
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多