【发布时间】:2011-03-24 05:30:20
【问题描述】:
如何在我的规范中添加翻译测试?类似的东西:
flash[:error].should == I18n.translate 'error.discovered'
这当然行不通。如何让它发挥作用?
我想确保我收到某个错误。
【问题讨论】:
-
试试 app.t('error.discovered') 真的没有线索,但也许你很幸运 :)
标签: ruby-on-rails rspec
如何在我的规范中添加翻译测试?类似的东西:
flash[:error].should == I18n.translate 'error.discovered'
这当然行不通。如何让它发挥作用?
我想确保我收到某个错误。
【问题讨论】:
标签: ruby-on-rails rspec
在我的代码中,一个使用 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
所以我不知道你为什么说不可能?
【讨论】:
不确定这是否是最佳选择,但在我的 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
我不确定如何在不需要 I18n.t 的情况下仅在规范中使用 t() 方法,所以我只是在 spec/support/utilities.rb中添加了一个小便利方法>:
def t(string, options={})
I18n.t(string, options)
end
更新:这些天来,我倾向于使用i18n-tasks gem 来处理与 i18n 相关的测试,而不是我在上面写的或之前在 StackOverflow 上回答过的内容。
我想在我的 RSpec 测试中使用 i18n,主要是为了确保我对所有内容都有翻译,即没有翻译遗漏。 i18n-tasks 可以通过对我的代码进行静态分析来做到这一点以及更多,因此我不再需要为所有 I18n.available_locales 运行测试(除了测试非常特定于语言环境的功能时,例如,从任何语言环境切换到系统中的任何其他语言环境)。
这样做意味着我可以确认系统中的所有 i18n 键实际上都有值(并且没有一个未使用或已过时),同时保持重复测试的数量,从而降低套件运行时间。
【讨论】:
假设控制器中的代码是:
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
【讨论】:
flash[:error]。方法存根替换 I18n.translate 并返回块中传递的值——错误消息文本本身并不重要,它可以是任何你喜欢的。