如何使用 i18m 将属性插入 rspec 测试以验证消息
How to insert an attribute into rspec test for validation messages using i18m
我的翻译文件设置了一些用于某些 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)>'
我找到了答案。我需要将属性的 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
我的翻译文件设置了一些用于某些 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)>'
我找到了答案。我需要将属性的 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