【发布时间】:2013-11-19 01:37:22
【问题描述】:
我想使用 RSpec 来确保我的可枚举类与 Ruby 的访问者模式兼容:
# foo.rb
class Foo
def initialize(enum)
@enum = enum
end
include Enumerable
def each(&block)
@enum.each(&block)
end
end
这是我的 rspec 文件:
# spec/foo_spec.rb
require 'rspec'
require './foo.rb'
describe Foo do
let(:items) { [1, 2, 3] }
describe '#each' do
it 'calls the given block each time' do
block = proc { |x| x }
block.should_receive(:call).exactly(items.size).times
Foo.new(items).each(&block)
end
end
end
但令人惊讶的是,我的示例在运行时失败了(使用 rspec v2.14.5):
# $ bundle exec rspec
Failures:
1) Foo#each calls the given block each time
Failure/Error: block.should_receive(:call).exactly(items.size).times
(#<Proc:0x007fbabbdf3f90@/private/tmp/rspec-mystery/spec/foo_spec.rb:8>).call(any args)
expected: 3 times with any arguments
received: 0 times with any arguments
# ./spec/foo_spec.rb:12:in `block (3 levels) in <top (required)>'
Finished in 0.00082 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/foo_spec.rb:11 # Foo#each calls the given block each time
更令人惊讶的是,当通过 ruby/irb 使用时,该类本身的行为完全符合我的预期:
# $ irb -r ./foo.rb
1.9.3-p125 :002 > f = Foo.new [1, 2, 3]
=> #<Foo:0x007ffda4059f70 @enum=[1, 2, 3]>
1.9.3-p125 :003 > f.each
=> #<Enumerator: [1, 2, 3]:each>
1.9.3-p125 :004 > block = proc { |x| puts "OK: #{x}" }
=> #<Proc:0x007ffda483fcd0@(irb):4>
1.9.3-p125 :005 > f.each &block
OK: 1
OK: 2
OK: 3
=> [1, 2, 3]
为什么 RSpec 没有注意到“块”实际上确实收到了 3 次“调用”消息?
【问题讨论】: