2

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.

Tintin81
  • 9,821
  • 20
  • 85
  • 178

1 Answers1

4

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
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • Awesome, thanks! This fixes all my controller specs. How about the feature specs, though? They still fail... – Tintin81 Feb 12 '14 at 12:58
  • `NoMethodError: undefined method 'metadata' for #` – Tintin81 Feb 12 '14 at 13:22
  • 1
    maybe a version issue, try to copy paste the first before each with `type` to check if that works – apneadiving Feb 12 '14 at 13:24
  • OK, I just tried `config.before :each, :type => :feature` but it gives me the same error. – Tintin81 Feb 12 '14 at 13:32
  • Done. But the `:type => :feature` spec still throws an error: `NameError: undefined local variable or method 'request' for #` – Tintin81 Feb 12 '14 at 13:46
  • 1
    yep, unfortunately few webdrivers let you set the headers, look at the capybara page, there is an example for rack, for selenium, it seems there is a workaround: http://blog.plataformatec.com.br/2011/03/configuring-user-agents-with-capybara-selenium-webdriver/ – apneadiving Feb 12 '14 at 13:53