2016-09-17 27 views
2

設置我已經重寫方法default_url_options在application.rb中爲什麼Rspec的忽略default_url_options我在application_controller.rb

class 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網址選項(區域),以及如何可以告訴RSpec的做到這一點?

回答

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