Reputation: 2089
I'm having a hard time understanding how to use mocha mocking library for certain type of unit tests in Rails.
I have a controller, which initializes an object from a helper library, and then calls a function on it. My code looks similar to
class ObjectsController < ApplicationController
before_action :set_adapter
def index
response = @adapter.get_objects
render json: response
end
private
def set_adapter
arg = request.headers["X-ARG"]
@adapter = Adapter::Adapter.new(arg)
end
end
In my tests, I want mock the adapter to make sure that the get_objects() method is called. I'm trying to figure out what is the best way to implement this kind of tests, but I seem to be stuck on getting the idea on how to mock an existing object within a class.
Can anyone help me out?
Upvotes: 5
Views: 1739
Reputation: 1959
You could stub it like this:
adapters = mock('object')
adapters.expects(:get_objects)
Adapter::Adapter.expects(:new).with('<X-ARG-HEADER-HERE>').returns(adapters)
# Run rest of test here to trigger calling the index method
Hope it helps.
Upvotes: 2