Josh Hadik
Josh Hadik

Reputation: 433

How do you test that a Ruby method returns the result of another Ruby method?

Let's say I have two methods where one of the methods returns the result of the other method:

class SomeClass
  def method_a
    method_b
  end

  def method_b 
    'foobar'
  end
end

And I'm trying to test method_a without 'retesting' the logic from method b. To do that, I use something like this:

RSpec.describe SomeClass do
  subject { SomeClass.new }

  describe '#method_a' do
    expect(subject).to receive(:method_b)
    subject.method_a
  end
end

Usually this works just fine, however, in this case it is important that method a actually returns the result of method b, not just that it gets called. How can I do this? (Perhaps theirs a method for this? Potentially named something like #receive_and_return or #return_value_of_method_call or something along those lines.)

Upvotes: 0

Views: 546

Answers (1)

王信凱
王信凱

Reputation: 463

you need 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

Upvotes: 1

Related Questions