Yaml中的Ruby正则表达式

时间:2017-01-25 10:32:14

标签: ruby cucumber yaml

我是YAML的新手,我正在尝试编写一些语言翻译测试。我的想法是我有一个YAML文件,其中包含相同文本的英语和威尔士语版本。我想知道如何在YAML中的字符串中使用正则表达式?

示例:

我有这个基本测试:

#Gherkin
And I expect to see payment confirmation for "Dave"

#Step Def
    And /^I expect to see payment confirmation for "(.*?)"$/ do |user|
      expect(page).to have_text "Payment successful for #{user} - Reference: 000000"
end

YAML条目:

"Payment successful for Dave reference: 000000"
 - welsh: "Taliad llwyddiannus ar gyfer Dave Cyfeirnod: 000000"

我可以在该YAML条目中参数化Dave,因为测试套件涵盖了数百名用户。

由于

1 个答案:

答案 0 :(得分:6)

如果要将文本插入到YAML中,则需要用%{keyword}替换要插值的单词,其中关键字是用于指示要在其中插入哪些数据的键。

如果您使用Rails,则可以使用this section of the I18n guide中概述的t辅助方法。

# The YAML file
en:
  payment_succeeded: "Payment successful for %{first_name} reference: %{reference_number}"
wh: 
  payment_succeeded: "Taliad llwyddiannus ar gyfer %{first_name} Cyfeirnod: %{reference_number}"

# Rails Controller / View / Model
t(:payment_succeeded, first_name: 'Dave', reference_number: '000000')

如果您想要纯ruby实现,可以使用Kernel::format方法。

# The YAML file
# NOTE: This can be in any format, as long as you use %{keyword} in places where you want the data to be interpolated
translations:
  english: "Payment successful for %{first_name} reference: %{reference_number}"
  welsh: "Taliad llwyddiannus ar gyfer %{first_name} Cyfeirnod: %{reference_number}"

# Ruby
translations = YAML.load(File.read('translations.yaml'))
string = format(translations[:translations][:welsh], first_name: 'Dave', reference_number: '000000')

希望这有帮助。