带有被测对象的文件:foo.rb
class Foo
def a_string
"abcdef8"
end
end
规格文件:foo_spec.rb
require_relative "./foo"
describe Foo do
let(:foo) {Foo.new}
let(:my_matcher) {/^[a-z]+(\d)$/}
# This test passes
it "should match and pass" do
my_str = foo.a_string
my_matcher # <--- why does this affect the test?
matcher = my_str.match(my_matcher)
8.should == matcher[1].to_i
end
# This test fails
it "should also match and pass but fails" do
my_str = foo.a_string
#my_matcher #<---- the only change between the tests
matcher = my_str.match(my_matcher) #<---- when called here, it behaves differently
8.should == matcher[1].to_i
end
end
rspec foo_spec.rb
.F
Failures:
1) Foo should also match and pass but fails
Failure/Error: 8.should == matcher[1].to_i
NoMethodError:
undefined method `[]' for /^[a-z]+(\d)$/:Regexp
# ./foo_spec.rb:18:in `block (2 levels) in <top (required)>'
Finished in 0.00095 seconds
2 examples, 1 failure
Failed examples:
rspec ./foo_spec.rb:14 # Foo should also match and pass but fails
两个测试的唯一区别是是否my_matcher
被调用。我在检查 my_matcher (ie p my_matcher
) 时第一次注意到这个问题,但它也发生在仅调用my_matcher
.
这是一个错误,还是我做错了什么?也许它与捕获正则表达式数据有关?
这似乎是非常奇怪的行为,尤其是对于 ruby。
对于它的价值,这是一个简单的(如果稍微不那么干燥)修复。如果my_matcher
在it
块中声明它按预期工作。