如何使用and_yield测试多个方法调用

时间:2015-02-21 10:02:24

标签: ruby rspec

在非常沮丧之后,我发现我误解了.and_yield的工作原理并且与.and_return不同。每次接受块的方法被调用为多个.and_yield时,多个.and_return不会产生不同的值,而是产生所有多个.and_yield class Foo def self.ask &block yield gets.chomp end end describe Foo do it 'should enforce `foo`' do allow(Foo).to receive(:ask).and_yield('bar').and_yield('foo') expect(Foo).to receive(:ask).twice output = nil until output == 'foo' Foo.ask do |response| output = response end end end end &#39}每个方法调用。这个例子应该更好地帮助解释......

Foo.ask

在此示例中,测试失败,因为until仅被调用一次,因为在rspec产生2个值后,测试中的逻辑得到满足。除了.and_return逻辑之外,我还需要测试块逻辑。使用.and_yield,这可以正常工作,因为它只能为每个方法调用返回一个值,但是如何使用{{1}}获得相同的行为?

1 个答案:

答案 0 :(得分:0)

首先,and_return并不像您认为的那样行事。如果多次调用and_return,则应用最近传递的参数,如下所示,传递:

describe 'and_return behavior' do
  it 'returns the last value specified' do
    dbl = double
    allow(dbl).to receive(:foo).and_return(1).and_return(2)
    expect(dbl.foo).to eq(2)
  end
end

有一种内置的方法告诉and_return为连续调用返回不同的值,即传递多个参数,如https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/returning-a-value#specify-different-return-values-for-multiple-calls

中所述

但是,对于and_yield的连续调用,没有内置的方法可以产生不同的值。为了实现这一点,您需要提供自己的实现,如https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation

中所述