假设我有两种方法,其中一种方法返回另一种方法的结果:
class SomeClass
def method_a
method_b
end
def method_b
'foobar'
end
end
我正在尝试测试method_a而不从方法b中“重新测试”逻辑。要做到这一点,我使用这样的东西:
RSpec.describe SomeClass do
subject { SomeClass.new }
describe '#method_a' do
expect(subject).to receive(:method_b)
subject.method_a
end
end
通常这很好用,但是,在这种情况下,重要的是方法a实际返回方法b的结果,而不仅仅是它被调用。我怎样才能做到这一点? (也许他们的方法是这样的?潜在地命名为#receive_and_return或#return_value_of_method_call或类似的东西。)
答案 0 :(得分:1)
你需要rspec-mocks(https://relishapp.com/rspec/rspec-mocks/docs/configuring-responses/returning-a-value#specify-a-return-value)
RSpec.describe SomeClass do
describe '#method_a' do
let(:some_class) { SomeClass.new }
context 'method_b return foobar' do
before { allow(some_class).to receive(:method_b).and_return('foobar') }
it 'will return foobar' do
allow(some_class).to receive(:method_b).and_return('foobar')
expect(some_class.method_a).to eq('foobar')
end
end
context 'method_b return barbar' do
before { allow(some_class).to receive(:method_b).and_return('barbar') }
it 'will return barbar' do
expect(some_class.method_a).to eq('barbar')
end
end
end
end