测试 Rspec 的 and_yield ()

linjunpop · 2012年04月17日 · 最后由 linjunpop 回复于 2012年04月18日 · 2844 次阅读

在 rpsec-mocks 的 README 这样写

double.should_receive(:msg).and_yield(values,to,yield)
double.should_receive(:msg).and_yield(values,to,yield).and_yield(some,other,values,this,time)
  # for methods that yield to a block multiple times



看不明白是什么意思,values,to,yield 分别是什么?

Source 是这样:

# Tells the object to yield one or more args to a block when the message
# is received.
#
# @example
#
#   stream.stub(:open).and_yield(StringIO.new)
def and_yield(*args, &block)
  if @args_to_yield_were_cloned
    @args_to_yield.clear
    @args_to_yield_were_cloned = false
  end

  if block
    @eval_context = Object.new
    @eval_context.extend RSpec::Mocks::InstanceExec
    yield @eval_context
  end

  @args_to_yield << args
  self
end


for methods that yield to a block multiple times

据我理解应该是 and_yield 在带有 block 的函数环境下的使用 value, to 是参数,yield 是外部的代码块. 比如:

def and_yield(*args, &block)
  if block
        yield bb
  end
  puts args
end

def test a
  and_yield(1,2,a,yield)
end

test 3 do 
  puts 'yy'
end

这里 values,to,yields 是范指 表示所有参数原封不动的 yield 出去。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号