2

我最近before_action在我的 a 中添加了一些新代码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

问题是该extract_locale_from_accept_language_header功能破坏了我所有的控制器规格(即它们现在都失败了)。似乎 RSpec 无法检测到任何HTTP_ACCEPT_LANGUAGE.

有没有办法为我的所有控制器规格伪造这种行为?

以下确实有效,但有点难看,因为我必须将该行添加request.env...到我的所有控制器测试中。我有很多。

require 'spec_helper'

describe UsersController do

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

  ...

end

有人可以帮忙吗?

谢谢。

4

1 回答 1

4

在您的 spec_helper 中执行此操作:

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

试试这个控制器和功能规格:

config.before(:each) do |example|
  if [:controller, :feature].include?(example.metadata[:type])
    request.env['HTTP_ACCEPT_LANGUAGE'] = "en" # ugly
  end
end
于 2014-02-12T12:32:36.697 回答