添加I18n翻译到rspec测试
如何在我的规格中添加翻译测试? 就像是 :
flash[:error].should == I18n.translate 'error.discovered'
这当然不起作用。 如何使其工作?
我想确保我收到一些错误。
在我的代码中,使用rspec2的rails3项目,这正是我写的行:
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]
在我需要翻译检查的spec文件中,我的测试看起来像:
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
更新 :这些天我倾向于使用i18n-tasks gem来处理与i18n相关的测试,而不是我上面写的或者之前在StackOverflow上回答的问题。
我想在我的RSpec测试中使用i18n主要是为了确保我的所有内容都有翻译,即没有错过任何翻译。 i18n-tasks可以通过我的代码的静态分析来做到这一点,所以我不再需要为所有I18n.available_locales
运行测试(除了测试特定于语言环境的function时,例如,从任何语言环境切换)到系统中的任何其他语言环境)。
这样做意味着我可以确认系统中的所有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