Search code examples
ruby-on-railsrspecrspec-rails

RSpec mock service and corresponding method


I want to mock a service that returns the integer 0 when called with get_auth_key.api_response_code.

This is what I have so far:

  before(:each) do
    PolicyObjects::BpointRequestPolicy.any_instance.stub(:get_auth_key).and_return(OpenStruct.new(api_response_code: 0))
  end

I would like to avoid creating a class for this in the test as I believe it's overkill. Somewhere in the codebase, response = PolicyObjects::BpointRequestPolicy.new(...) gets called and then compared: if response.api_response_code == 0. I would like it to return 0 to hit conditionals in my test.

What is the best practice or easiest way of doing this?


Solution

  • This is a great use case for a double or better an instance_double if you know the class you're mocking out:

    let(:api_resonse) { instance_double("SomeResponseClass", api_response_code: 0) }  
    
    before(:each) do 
      PolicyObjects::BpointRequestPolicy.any_instance.stub(:get_auth_key).and_return(api_response)
    end