rubocop 中的 "Ambiguous regexp literal" 是什么?

What is "Ambiguous regexp literal" in rubocop?

代码如下

expect(foo).to match /#{MyGem.config.environment_name}/

触发 rubocop 问题

Warning: Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the / if it should be a division.

有人可以解释问题是什么以及如何解决吗?

此时正在抱怨:

match /#{MyGem.config.environment_name}/

不清楚您是将两个数字相除还是将 RegExp 文字传递给方法调用。

在这种特殊情况下,由于您只是检查字符串中是否存在子字符串,因此最好使用 RSpec #include 匹配器,如下所示:

expect(foo).to include MyGem.config.environment_name

解决此问题的另一种方法是按照 rubocop 的建议简单地添加括号。变化

expect(foo).to match /#{MyGem.config.environment_name}/

expect(foo).to match(/#{MyGem.config.environment_name}/)