Question

I recently added some new code to a before_action in my ApplicationController:

class ApplicationController < ActionController::Base

  before_action :set_locale

  def set_locale
    I18n.locale = (session[:locale] || params[:locale] || extract_locale_from_accept_language_header).to_s.downcase.presence || I18n.default_locale
  end

  private

  def extract_locale_from_accept_language_header
    request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
  end

end

The problem is that the extract_locale_from_accept_language_header function disrupts all my controller specs (i.e. they all fail now). It seems that RSpec can't detect any HTTP_ACCEPT_LANGUAGE.

Is there a way to fake this behaviour for all my controller specs?

The following does work but is a bit ugly since I would have to add the line request.env... to all my controller tests. And I have many of them.

require 'spec_helper'

describe UsersController do

  before :each do
    @user = FactoryGirl.create(:user)
    request.env['HTTP_ACCEPT_LANGUAGE'] = "en" # ugly
  end

  ...

end

Can anybody help?

Thanks.

Was it helpful?

Solution

Do it in in your spec_helper:

config.before :each, type: :controller do
  request.env['HTTP_ACCEPT_LANGUAGE'] = "en"
end

Try this for both controller and feature specs:

config.before(:each) do |example|
  if [:controller, :feature].include?(example.metadata[:type])
    request.env['HTTP_ACCEPT_LANGUAGE'] = "en" # ugly
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top