我的翻译文件设置有一些ActiveRecord验证的自定义错误消息,但是当我将%{attribute}
传递给它时,测试失败。如何使用rspec测试来使用翻译?
en.locale
en:
activerecord:
errors:
models:
account:
attributes:
name:
invalid: "%{attribute} must only include numbers and letters"
rspec测试
it "is invalid with special characters" do
account = FactoryGirl.build(:account, name: "test_account_*name")
account.valid?
expect(account.errors[:name]).to include(I18n.t('activerecord.errors.models.account.attributes.name.invalid'))
end
结果
20) Account is invalid with special characters
Failure/Error: expect(account.errors[:name]).to include(I18n.t('activerecord.errors.models.account.attributes.name.invalid'))
expected ["Name must only include numbers and letters"] to include "%{attribute} must only include numbers and letters"
# ./spec/models/account_spec.rb:29:in `block (2 levels) in <top (required)>'
答案 0 :(得分:1)
我找到了答案。我需要将human_attribute_name
属性作为参数attribute
传递给翻译。
测试现在通过如下:
it "is invalid with special characters" do
account = FactoryGirl.build(:account, name: "test_account_*namre")
account.valid?
expect(account.errors[:name]).to include(I18n.t('activerecord.errors.models.account.attributes.name.invalid', attribute: Account.human_attribute_name(:name)))
end