在Rspec服务测试中包含I18n帮助程序

use*_*003 3 rspec ruby-on-rails rails-i18n

我在我的应用程序中使用了服务,这不是"标准"应用程序组件之一.

假设我的规格测试如下

需要"rails_helper"

# spec/services/create_user.rb
RSpec.describe CreateUser, type: :service do
  it "returns the error message" do
    error_message = Foo.new.errors
    expect(error_message).to eq(t("foo.errors.message"))
  end
Run Code Online (Sandbox Code Playgroud)

结束

只测试返回的字符串是否与特定的翻译字符串匹配.

但是,这会引发错误,因为帮助t()程序不可用.

我可以将它明确地称为I18n.t(),但出于我自己的好奇心,我如何包含正确的模块以获得调用速记形式的奢侈品?

谢谢!

小智 7

您应该能够使用以下内容将其添加到RSpec配置中;

RSpec.configure do |config|
  config.include AbstractController::Translation
end
Run Code Online (Sandbox Code Playgroud)

这意味着你可以只使用t()而不是I18n.t()