谁能给我解释一下为什么会这样?
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
最佳答案
这对我来说似乎是非常*出乎意料的行为,但我已经解决了这个问题。 String#match 的 Ruby 文档说
Converts pattern to a Regexp (if it isn’t already one)
但这种“转换”似乎只是将“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
!!!!
关于ruby-on-rails - Rspec should match is false 但 eq 应该为真吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12319759/