ruby-on-railsrubyrspecmockingstubbing

In RSpec, how to mock a method so that it returns its argument


Let's say I have a class with a method that modifies and returns a hash. When testing the class the method will be called, but for the purposes of the test, I want it to return its argument unmodified.

class MyClass 
  def my_method(h)
    # method body that modifies h before returning it
    h.merge!(some_new_key: "some new value")
  end
end

That is, I want to do something like this...

allow(instanceOfMyClass).to receive(:my_method).with( a_hash ).and_return( a_hash )

... where a_hash is an arbitrary hash, not explicitly specified in my test. In the test I want instanceOfMyClass.my_method(a_hash) to return a_hash, the same argument it was passed.

Can this be done in RSpec? If so, how?


Solution

  • If you don't need the original implementation at all, you can pass a block implementation to replace the method with:

    allow(instance_of_my_class).to receive(:my_method) { |hash| hash }
    

    Or via itself: (which refers to the argument)

    allow(instance_of_my_class).to receive(:my_method, &:itself)