将I18n转换添加到rspec测试中

问题描述 投票:26回答:3

如何为我的规格添加翻译测试?像:

flash[:error].should == I18n.translate 'error.discovered'

这当然行不通。如何运作?

我想确保我得到一定的错误。

ruby-on-rails rspec
3个回答
65
投票

在我的代码中,一个使用RSpec 2的Rails 3项目,正是我写的那行:

describe "GET 'index'" do
  before do
    get 'index'
  end
  it "should be successful" do
    response.should be_redirect
  end

  it "should show appropriate flash" do
    flash[:warning].should == I18n.t('authorisation.not_authorized')
  end
end

所以我不确定您为什么说这不可能?


13
投票

不确定这是否是最佳选择,但是在我的Rails3 / RSpec2应用程序中,我通过以下方式在RSpec中测试了所有语言环境翻译:

我在config / initializers / i18n.rb文件中设置了可用的语言环境:

I18n.available_locales = [:en, :it, :ja]

并且在我需要翻译检查的规范文件中,我的测试看起来像:

describe "Example Pages" do   

  subject { page }

  I18n.available_locales.each do |locale|

    describe "example page" do
      let(:example_text) { t('example.translation') }

      before { visit example_path(locale) }

      it { should have_selector('h1', text: example_text) }
      ...
    end
    ...   
  end
end

我不确定如何在不需要t()的情况下仅使I18n.t方法在规范中可用,所以我只是在spec / support / utilities.rb中添加了一种便捷的方法:

def t(string, options={})
  I18n.t(string, options)
end

Update:这些天来,我倾向于使用i18n-tasks gem处理与i18n相关的测试,而不是我上面写的或之前在StackOverflow上回答的内容。

我想在我的RSpec测试中使用i18n,主要是为了确保我对所有内容都拥有翻译,即不会错过任何翻译。 i18n任务可以通过对我的代码进行静态分析来做到这一点,甚至更多,因此,我不再需要对所有I18n.available_locales进行测试(除了测试非常特定于语言环境的功能时,例如从任何语言环境切换时)到系统中的任何其他语言环境。

这样做意味着我可以确认系统中的所有i18n密钥实际上都具有值(并且没有任何值是未使用或已过时的,同时又减少了重复测试的次数,从而减少了套件的运行时间。


4
投票

假设控制器中的代码为:

flash[:error] = I18n.translate 'error.discovered'

您可以存根'翻译':

it "translates the error message" do
  I18n.stub(:translate) { 'error_message' }
  get :index # replace with appropriate action/params
  flash[:error].should == 'error_message'
end
© www.soinside.com 2019 - 2024. All rights reserved.