Rspec 3.0 How to mock a method replacing the parameter but with no return value? Rspec 3.0 How to mock a method replacing the parameter but with no return value? ruby ruby

Rspec 3.0 How to mock a method replacing the parameter but with no return value?


How to set a default value that is explained at

and_call_original can configure a default response that can be overriden for specific args

require 'calculator'RSpec.describe "and_call_original" do  it "can be overriden for specific arguments using #with" do    allow(Calculator).to receive(:add).and_call_original    allow(Calculator).to receive(:add).with(2, 3).and_return(-5)    expect(Calculator.add(2, 2)).to eq(4)    expect(Calculator.add(2, 3)).to eq(-5)  endend

Source where I came to know about that can be found at https://makandracards.com/makandra/30543-rspec-only-stub-a-method-when-a-particular-argument-is-passed


For your example, since you don't need to test the actual result of test_method, only that puts gets called in it passing in param, I would just test by setting up the expectation and running the method:

class Test  def test_method(param)    puts param  endenddescribe Test do  let(:test) { Test.new }  it 'says hello via expectation' do    expect(test).to receive(:puts).with('hello')    test.test_method('hello')  end  it 'says goodbye via expectation' do    expect(test).to receive(:puts).with('goodbye')    test.test_method('goodbye')  endend

What it seems you're attempting to do is set up a test spy on the method, but then I think you're setting up the method stub one level too high (on test_method itself instead of the call to puts inside test_method). If you put the stub on the call to puts, your tests should pass:

describe Test do  let(:test) { Test.new }  it 'says hello using a test spy' do    allow(test).to receive(:puts).with('hello')    test.test_method('hello')    expect(test).to have_received(:puts).with('hello')  end  it 'says goodbye using a test spy' do    allow(test).to receive(:puts).with('goodbye')    test.test_method('goodbye')    expect(test).to have_received(:puts).with('goodbye')  endend