由default_locale打破的Rspec视图规范

dja*_*o09 2 locale rspec ruby-on-rails view

我最近对我的Rails应用进行了本地化,并添加了一个默认的"en"区域设置(我按照此处的说明将区域设置添加到我的网址中).这打破了我的大多数规格; 除了我的View规范之外,我已经能够找到所有这些解决方案/解决方法.

这是一个基本视图规范的例子,我的文章查看规范:

RSpec.describe 'articles/index', type: :view do
  before(:each) do
    assign(:articles, [
      FactoryGirl.create(:article, number: '11.22.33'),
      FactoryGirl.create(:article, number: '22.33.44')
    ])
  end

  it 'renders a list of articles' do
    render
  end
end
Run Code Online (Sandbox Code Playgroud)

此规范导致以下错误:

 1) articles/index renders a list of articles
     Failure/Error: render
     ActionView::Template::Error:
       No route matches {:action=>"show", :controller=>"articles", :id=>nil, :locale=>#<Article id: 2, number: "11.22.33", criminal_code_id: 3, description: nil, created_at: "2015-05-25 08:58:56", updated_at: "2015-05-25 08:58:56">} missing required keys: [:id, :locale]
Run Code Online (Sandbox Code Playgroud)

好像有三个问题:

  1. Rspec应该使用动作"index"而不是"show"
  2. "索引"操作应该没有必需的:id键
  3. 语言环境应该是"en"而不是我创建的其中一篇文章.

以下是我的相关路线:

Rails.application.routes.draw do
  scope ':locale', locale: /#{I18n.available_locales.join("|")}/ do
    resources :articles do
      collection do
        get 'custom_json', constraints: { format: :json }, defaults: { format: :json }
      end
    end

    get "*path", to: redirect("/#{I18n.default_locale}") # handles /en/fake/path/whatever
  end

  get '', to: redirect("/#{I18n.default_locale}") # handles /
  get '*path', to: redirect("/#{I18n.default_locale}/%{path}") # handles /not-a-locale/anything
end
Run Code Online (Sandbox Code Playgroud)

这是我的应用程序控制器的相关部分:

before_action :set_locale

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

def default_url_options(options = {})
  { locale: I18n.locale }.merge options
end
Run Code Online (Sandbox Code Playgroud)

我的文章视图位于app/views/articles/index.html.erb(关于它没有什么特别之处).

任何人都知道如何让View规范与locales玩得很好?

Jos*_*eim 9

以下内容可以帮助您:

# Set locale for view specs, see https://github.com/rspec/rspec-rails/issues/255#issuecomment-2865917
class ActionView::TestCase::TestController
  def default_url_options(options = {})
    {locale: I18n.default_locale}
  end
end

# Set locale for feature specs, see https://github.com/rspec/rspec-rails/issues/255#issuecomment-24698753
RSpec.configure do |config|
  config.before(:each, type: :feature) do
    default_url_options[:locale] = I18n.default_locale
  end
end
Run Code Online (Sandbox Code Playgroud)

它对我的情况有帮助.尽管如此,经过这么多年的Rails I18n之后我仍然不得不关心自己这样的事情.