2012-09-07 31 views
1

任何人都可以向我解释为什么会发生这种情况吗?Rspec应匹配是错误的,但应该是真实的?

get :robots 
response.should render_template("no_index") 
response.body.should match "User-agent: *\nDisallow: /\n" 

Failure/Error: response.body.should match "User-agent: *\nDisallow: /\n" 
    expected "User-agent: *\nDisallow: /\n" to match "User-agent: *\nDisallow: /\n" 
# ./spec/controllers/robots_controller_spec.rb:12:in `block (3 levels) in <top (required)>' 

get :robots 
response.should render_template("no_index") 
response.body.should eq "User-agent: *\nDisallow: /\n" 

通行证?

这似乎相关(IRB):

1.9.2p318 :001 > "User-agent: *\nDisallow: /\n".match "User-agent: *\nDisallow: /\n" 
=> nil 

回答

3

这似乎很可能* *预期的行为,但我已经找到了问题。弦乐#匹配Ruby的文件说

转换模式是正规表达式(如果它尚未之一)

但这种“转换”似乎只是意味着改变“富”到/富/,没有做任何转义或任何事情。因此,例如,

1.9.2p318 :014 > "User-agent: *\nDisallow: /\n".match /User-agent: \*\nDisallow: \/\n/ 
=> #<MatchData "User-agent: *\nDisallow: /\n"> 

如果使用单引号,但在逃逸添加了特殊的正则表达式字符字符串匹配也可以工作:

1.9.2p318 :015 > "User-agent: *\nDisallow: /\n".match 'User-agent: \*\nDisallow: \/\n' 
=> #<MatchData "User-agent: *\nDisallow: /\n"> 

但是,如果使用双引号,它仍然无法正常工作,因为新行的:

1.9.2p318 :013 > "User-agent: *\nDisallow: /\n".match "User-agent: \*\nDisallow: \/\n" 
=> nil 

!!!!

1

只是一个猜测,但是匹配使用正则表达式,其中*部分是指“任何数量的空格”,而不是“空间 - 和 - *”。逃避(或其他)字符。

response.body.should eq 'User-agent: \*\nDisallow: /\n' 
相关问题