Ruby on rails Rspec应匹配为假,但eq应为真?
有人能解释一下为什么会发生这种情况吗Ruby on rails Rspec应匹配为假,但eq应为真?,ruby-on-rails,ruby,ruby-on-rails-3,rspec,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" t
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)>'
通行证
这似乎与irb有关:
1.9.2p318 :001 > "User-agent: *\nDisallow: /\n".match "User-agent: *\nDisallow: /\n"
=> nil
您的字符串将以正则表达式的形式与自身匹配,这很可能会由于特殊字符(如斜杠和asterix)而失败 eq确实是在您的案例中使用的正确匹配器
您的字符串将以正则表达式的形式与自身匹配,这很可能会由于特殊字符(如斜杠和asterix)而失败 eq确实是在您的案例中使用的正确匹配器
只是猜测,但匹配使用正则表达式,其中*部分表示任意数量的空格,而不是空格和-*。转义该字符或其他字符
response.body.should eq 'User-agent: \*\nDisallow: /\n'
只是猜测,但匹配使用正则表达式,其中*部分表示任意数量的空格,而不是空格和-*。转义该字符或其他字符
response.body.should eq 'User-agent: \*\nDisallow: /\n'
对我来说,这似乎是非常不可能的行为,但我已经解决了这个问题。Stringmatch的Ruby文档说 如果模式不是正则表达式,则将其转换为正则表达式 但这种转换似乎只是意味着将foo更改为/foo/,而不进行任何转义或其他操作。因此,例如
1.9.2p318 :014 > "User-agent: *\nDisallow: /\n".match /User-agent: \*\nDisallow: \/\n/
=> #<MatchData "User-agent: *\nDisallow: /\n">
对我来说,这很可能是一种“出乎意料”的行为,但我已经发现了问题所在。Stringmatch的Ruby文档说 如果模式不是正则表达式,则将其转换为正则表达式 但这种转换似乎只是意味着将foo更改为/foo/,而不进行任何转义或其他操作。因此,例如
1.9.2p318 :014 > "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