我是Ruby的新手。我正在试图弄清楚如何编写嵌套的case语句。这是我想要做的一个例子:
# cucumber, webrat paths.rb
def path_to(page_name)
case page_name
when /the "?(.*)"? event registration homepage/ then
case $1
when '2011 CIO GL Global' then '/event/index/id/236'
when '2011 CIO IS Chicago' then '/event/index/id/275'
when '2011 CIO ES Denver' then '/event/index/id/217'
when '2011 CIO ES Vancouver, BC' then '/event/index/id/234'
else
raise "Can't find mapping for \"#{$1}\" to a path.\n" +
"Now, go and add a mapping in #{__FILE__}"
end
when /the contact match verification page/
'/attendee/user-verification'
end
end
在我的功能文件中,它说:
When I go to the "2011 CIO IS Chicago" event registration homepage
这个步骤失败了,因为它引发了上面提到的异常,即使我在上面的case语句中定义了它。我做错了什么?
答案 0 :(得分:4)
是的,第二个问号混淆了正则表达式。
表达式:
.*b?
可以用两种方式匹配字符串“axb”,或者。*匹配整个事物,或者匹配'ax'和'b?'。匹配'b'。正则表达式算法是“贪婪的” - 它尽可能早地匹配尽可能多的匹配。
我将正则表达式重写为:
when /the "?([^"]*)"? event registration homepage/ then
确保$ 1最终没有任何双引号...
答案 1 :(得分:1)
它对我有用。你是如何测试它的?
更新:啊哈,这是因为你的正则表达式与尾随引号匹配,所以$ 1以引号结尾,而你的内部情况不存在。
有几种方法可以解决这个问题。
"?[^"]*"?
..."?'
"?(.*?)"?
。答案 2 :(得分:1)
更改
when /the "?(.*)"? event registration homepage/ then
到
when /the "?(.*)" event registration homepage/ then
答案 3 :(得分:0)
问题在于你的正则表达式。请尝试删除最后一个?
,因为它会导致"
成为可选项,并且前面的贪婪搜索(.*)
会将其置于匹配$1
中。
观察:
> s = 'the "2011 CIO IS Chicago" event registration homepage'
> /the "?(.*)"? event registration homepage/.match s #=> <MatchData "the \"2011 CIO IS Chicago\" event registration homepage" 1:"2011 CIO IS Chicago\"">
> $1 #=> "2011 CIO IS Chicago\""
> /the "?(.*)" event registration homepage/.match s #=> #<MatchData "the \"2011 CIO IS Chicago\" event registration homepage" 1:"2011 CIO IS Chicago">
> $1 #=> "2011 CIO IS Chicago"
修改:如果您希望"
是可选的,则可能需要执行以下操作:(?:"(.*)"|(.*))
。然后你需要使用一个nil guard来找出返回的引用。 $1 || $2
。
答案 4 :(得分:0)
我会稍微改变一下。在你的黄瓜功能中,我建议改变措辞:
When I go to the registration homepage for the event named "2011 CIO IS Chicago"
在你的paths.rb
文件中,我会用一个正则表达式来处理所有事件,如下所示:
when /the registration homepage for the event named "?(.*)"?/ then
event = Event.find_by_name($1)
raise "could not find an event with name: #{$1}" if event.blank?
event_path(event)
# or create the route manually like so:
# "event/index/id/#{event.id}"
这依赖于您的Event
模型,该模型具有可以找到给定名称的事件的方法(在本例中我假设find_by_name
),以及为:events
设置的资源丰富的路线。