Rspec匹配是假的但是eq是真的吗?

时间:2012-09-07 14:07:53

标签: ruby-on-rails ruby ruby-on-rails-3 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 个答案:

答案 0 :(得分:3)

这对我来说似乎很可能是*非预期的行为,但我已经找到了问题。 String#match的Ruby文档说

  

将模式转换为Regexp(如果它还不是一个)

但是这种“转换”似乎只是意味着将“foo”更改为/ foo /,而不进行任何转义或任何操作。所以,例如,

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 :(得分:1)

你的字符串与自身匹配(作为正则表达式),由于斜杠和星号等特殊字符,它很可能会失败。

eq确实是在你的情况下使用的正确匹配器。

http://rspec.rubyforge.org/rspec/1.1.9/classes/Spec/Matchers.html#M000437

答案 2 :(得分:1)

只是一个猜测,但匹配使用正则表达式,其中*部分表示“任意数量的空格”,而不是“space-and- *”。逃避那个(或其他一些)角色。

response.body.should eq 'User-agent: \*\nDisallow: /\n'