2015-08-18 39 views
0

在我config.routes.rb文件:如何設置rspec測試在Rails中使用默認語言環境?

scope '(:locale)' do 
    resources :techniques, path: '/applications' do 
     get '/complete_list' => 'techniques#complete_list' 
    end 
end 

在我Gemfile

group :development, :test do 
    gem 'rspec-rails' 
    gem 'byebug' 
    gem 'better_errors' 
    gem 'factory_girl_rails' 
    gem 'faker' 
end 

group :test do 
    gem 'poltergeist' 
    gem 'capybara' 
    gem 'launchy' 
    gem 'database_cleaner' 
end 

在我application_controller.rb

before_filter :set_locale 
    def set_locale 
    I18n.locale = params[:locale] || I18n.default_locale 
    end 

    def default_url_options(options = {}) 
    { locale: I18n.locale }.merge options 
    end 

在我的規格:

visit techniques_path 

它總是flunks:

I18n::InvalidLocale - "applications" is not a valid locale: 

而且它強調此行中我application_controller:

I18n.locale = params[:locale] || I18n.default_locale 

我可以做事情的工作,通過改變規格爲閱讀:

visit techniques_path(locale: :en) 

但我認爲在應用程序控制器中設置default_url_options會自動處理。我在這裏錯過了什麼?

回答

1

當你想從ApplicationController測試行爲,你需要一個所謂的匿名控制器,從ApplicationController繼承並是可測試控制器:

describe ApplicationController do 
    controller do 
    def index  
    end 
    end 

    describe "language setting" do  
    it "uses parameter" do 
     expect(I18n).to receive(:locale=).with('en') 
     get :index, locale: 'en' 
    end 

    it "falls back to default_locale" do 
     I18n.default_locale = 'nl' 
     expect(I18n).to receive(:locale=).with('nl') 
     get :index 
    end 
    end 
end 

編輯:我現在看到您需要添加的語言環境PARAM到功能測試。

當你想將參數傳遞到一個路徑,只需添加它們作爲哈希:

visit techniques_path({locale: 'en'}) 

不過,我覺得它不好的做法,在功能測試使用url_helpers。我假設「訪問」是功能/集成測試,因爲我沒有看到它在其他地方使用過。 相反,測試純粹的整合時,使用實際的字符串作爲路徑:

visit '/en/techniques/1234' 
visit "/en/techniques/@technique.id" 

這A.O。通知功能測試是一個單獨的應用程序:不依賴於應用程序內部狀態的應用程序。就好像它是一個使用瀏覽器單擊應用程序的「用戶」。使用firefox的用戶不能使用「technique_path」,他只能點擊鏈接,或者在瀏覽器欄中輸入URL。

相關問題