ruby-on-rails - Rspec should match is false 但 eq 应该为真吗?

标签 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 

最佳答案

这对我来说似乎是非常*出乎意料的行为,但我已经解决了这个问题。 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/

相关文章:

ruby-on-rails - 每个 Controller 方法中的代码

ruby-on-rails - Ruby 中的 sleep 语句不接受任何 Rails 转换

ruby-on-rails - PG::将字符串列更改为时间数据类型时出错时区

ruby-on-rails - rails 5 : Devise Gem password Encryption

ruby - Twilio 应用; twilio-ruby (3.4.2),SSL 错误

ruby-on-rails-3 - 无法批量分配 protected 属性 : address

ruby - 如何在两个已知点之间生成坐标

ruby-on-rails - 如何让 RSpec 和 Capybara 等待 ActionCable 完成足够长的时间?

ruby-on-rails - Ruby/Rails 中内置函数自定义版本的命名约定

ruby-on-rails - Rails 3 和 Angularjs 起源 http ://localhost is not allowed by Access-Control-Allow-Origin.